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
| type Queue struct { queue []string cond *sync.Cond }
func (q *Queue) Enqueue(item string) { q.cond.L.Lock() defer q.cond.L.Unlock()
q.queue = append(q.queue, item) fmt.Printf("pitting #{item} to queue, notify all\n") q.cond.Broadcast() }
func (q *Queue) Dequeue() string { q.cond.L.Lock() defer q.cond.L.Unlock()
if len(q.queue) == 0 { fmt.Println("no data available, wait") q.cond.Wait() } var item string item, q.queue = q.queue[0], q.queue[1:] return item }
func main() { q := Queue{queue: []string{}, cond: sync.NewCond(&sync.Mutex{})}
go func() { for { q.Enqueue("a") time.Sleep(time.Second * 2) } }()
for { q.Dequeue() time.Sleep(time.Second) } }
|