-
Notifications
You must be signed in to change notification settings - Fork 19
/
main.go
68 lines (55 loc) · 994 Bytes
/
main.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
59
60
61
62
63
64
65
66
67
68
package main
import (
"fmt"
"math/rand"
"sync"
)
type ConcurrentQueue struct {
queue []int32
lock sync.Mutex
}
func (q *ConcurrentQueue) Enqueue(item int32) {
q.lock.Lock()
defer q.lock.Unlock()
q.queue = append(q.queue, item)
}
func (q *ConcurrentQueue) Dequeue() int32 {
q.lock.Lock()
defer q.lock.Unlock()
if len(q.queue) == 0 {
panic("removing from an empty queue")
}
item := q.queue[0]
q.queue = q.queue[1:]
return item
}
func (q *ConcurrentQueue) Size() int {
q.lock.Lock()
defer q.lock.Unlock()
return len(q.queue)
}
const NUM_THREADS int = 1000000
func main() {
queue := &ConcurrentQueue{
queue: make([]int32, 0),
}
var wgE sync.WaitGroup
var wgD sync.WaitGroup
for i := 0; i < NUM_THREADS; i++ {
wgE.Add(1)
go func() {
queue.Enqueue(rand.Int31())
wgE.Done()
}()
}
for i := 0; i < NUM_THREADS; i++ {
wgD.Add(1)
go func() {
queue.Dequeue()
wgD.Done()
}()
}
wgE.Wait()
wgD.Wait()
fmt.Println("size:", queue.Size())
}