码迷,mamicode.com
首页 > 其他好文 > 详细

Golang sync.NewCond条件锁的用法

时间:2020-03-04 13:05:35      阅读:193      评论:0      收藏:0      [点我收藏+]

标签: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

Golang sync.NewCond条件锁的用法

标签:import   end   remove   sync   new   ati   main   cond   wait   

原文地址:https://www.cnblogs.com/ExMan/p/12408664.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!