-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.go
58 lines (45 loc) · 1.02 KB
/
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
package main
import (
"fmt"
"time"
)
type BlockingQueue struct {
channel chan interface{}
}
func NewBlockingQueue(size int) *BlockingQueue{
return &BlockingQueue {
channel: make(chan interface{}, size), // buffer channel of any size
}
}
func (q *BlockingQueue) Enqueue(item interface{}){
q.channel <- item
}
func (q *BlockingQueue) Dequeue() interface{} {
return <-q.channel
}
func (q *BlockingQueue) Size() int {
return len(q.channel)
}
func main() {
q := NewBlockingQueue(3)
// q.Enqueue(42)
// q.Enqueue("danger")
// fmt.Println(q.Dequeue())
// fmt.Println(q.Dequeue())
go func() {
for i := 1; i <= 5; i++ {
q.Enqueue(i)
fmt.Println("Enqueued:", i, " | Current size:", q.Size())
time.Sleep(1 * time.Second) // Simulate some work
}
}()
go func() {
for i := 1; i <= 5; i++ {
time.Sleep(2 * time.Second) // Simulate slower work to show blocking
value := q.Dequeue()
fmt.Println("Dequeued:", value, " | Current size:", q.Size())
}
}()
time.Sleep(10*time.Second)
fmt.Println(q.Size())
}