标签:import end remove sync new ati main cond wait
package main
import (
"fmt"
"sync"
"time"
)
func main() {
c := sync.NewCond(&sync.Mutex{})
queue := make([]interface{}, 0, 10)
removeFromQueue := func(delay time.Duration) {
time.Sleep(delay)
c.L.Lock()
queue = queue[1:]
fmt.Println("Remove from queue")
c.L.Unlock()
c.Signal()
}
for i := 0; i < 10; i++ {
c.L.Lock()
for len(queue) == 2 {
c.Wait()
}
fmt.Println("Adding to queue")
queue = append(queue, struct{}{})
go removeFromQueue(1 * time.Second)
c.L.Unlock()
}
}
程序输出如下,
Adding to queue
Adding to queue
Remove from queue
Adding to queue
Remove from queue
Adding to queue
Remove from queue
Adding to queue
Remove from queue
Adding to queue
Remove from queue
Adding to queue
Remove from queue
Adding to queue
Remove from queue
Adding to queue
Remove from queue
Adding to queue
标签:import end remove sync new ati main cond wait
原文地址:https://www.cnblogs.com/ExMan/p/12408664.html