美文网首页
Golang sync.NewCond条件锁的用法

Golang sync.NewCond条件锁的用法

作者: FredricZhu | 来源:发表于2019-06-08 15:11 被阅读0次
    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

    相关文章

      网友评论

          本文标题:Golang sync.NewCond条件锁的用法

          本文链接:https://www.haomeiwen.com/subject/vfuixctx.html