Go语言自定义线程安全的队列结构
程序员文章站
2023-12-28 14:25:16
...
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)
}
}