-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
58 lines (45 loc) · 954 Bytes
/
worker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"fmt"
"sync"
"time"
"github.com/google/uuid"
)
type Worker struct {
ID uuid.UUID
JobChan chan *Job
KillChan chan struct{}
}
type Job struct {
ID uuid.UUID
WorkTime int `json:"work_time"`
}
func SpawnWorker() *Worker {
id := uuid.New()
fmt.Println("Worker Spawned with ID:", id)
return &Worker{
ID: id,
JobChan: make(chan *Job),
KillChan: make(chan struct{}),
}
}
func (w *Worker) Start(wg *sync.WaitGroup, workers chan *Worker) {
outer:
for {
select {
case j := <-w.JobChan:
fmt.Printf("Worker with ID: %s executing the Job with ID: %s\n", w.ID, j.ID)
Execute(j)
fmt.Printf("Worker with ID: %s Finished the Job with ID: %s\n", w.ID, j.ID)
wg.Done()
workers <- w
case <-w.KillChan:
fmt.Printf("Woker with ID: %s Killed\n", w.ID)
break outer
}
}
}
func Execute(j *Job) {
// Mimic Work time
time.Sleep(time.Duration(j.WorkTime) * time.Millisecond)
}