package main
import (
"fmt"
"sync"
"time"
)
type Queue struct { // 队列
queue []interface{}
cond *sync.Cond
}
func GetDefaultQueue() *Queue { //获取默认队列
q := Queue{
queue: []interface{}{},
cond: sync.NewCond(&sync.Mutex{}),
}
return &q
}
func (q *Queue) Enqueue(item interface{}) { // 存值
q.cond.L.Lock()
defer q.cond.L.Unlock()
q.queue = append(q.queue, item)
q.cond.Broadcast()
}
func (q *Queue) Dequeue() interface{} { // 取值
q.cond.L.Lock()
defer q.cond.L.Unlock()
if len(q.queue) == 0 {
q.cond.Wait()
}
result := q.queue[0]
q.queue = q.queue[1:]
return result
}
func main() {
q := GetDefaultQueue()
go func() {
for {
q.Enqueue("a")
fmt.Println("存值:a")
time.Sleep(time.Second * 2)
}
}()
for {
result := q.Dequeue()
fmt.Println("取值:", result)
time.Sleep(time.Second)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)