-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadfun_queue.go
More file actions
79 lines (68 loc) · 1.51 KB
/
Copy paththreadfun_queue.go
File metadata and controls
79 lines (68 loc) · 1.51 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
// Dynamic dispatch via shared queue.
// Contrast with threadfun.go, which uses a static [start,end) partition.
//
// Here all goroutines share a single sharedQueue. The sync.Mutex protects
// the read-increment-release of nextJob so no job is claimed by two goroutines
// and no job is skipped.
//
// Note: a channel-based queue (chan int) is the more idiomatic Go equivalent,
// but sync.Mutex is used here to parallel the C and C# versions directly.
import (
"context"
"fmt"
"sync"
"time"
)
const (
workerCount = 4
jobCount = 20
)
type sharedQueue struct {
mu sync.Mutex
jobs []int
nextJob int
}
func (q *sharedQueue) pop() (int, bool) {
q.mu.Lock()
defer q.mu.Unlock()
if q.nextJob >= len(q.jobs) {
return 0, false
}
job := q.jobs[q.nextJob]
q.nextJob++
return job, true
}
func worker(id int, wg *sync.WaitGroup, ctx context.Context, q *sharedQueue) {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
default:
}
job, ok := q.pop()
if !ok {
return
}
fmt.Printf("Worker %d processing %d\n", id, job)
time.Sleep(200 * time.Millisecond)
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
jobs := make([]int, jobCount)
for i := range jobs {
jobs[i] = i
}
// All goroutines receive the same pointer — synchronization is inside the queue.
q := &sharedQueue{jobs: jobs}
var wg sync.WaitGroup
for i := 0; i < workerCount; i++ {
wg.Add(1)
go worker(i, &wg, ctx, q)
}
// Early-stop path: cancel()
wg.Wait()
}