当前位置:网站首页>go 条件变量
go 条件变量
2022-07-02 22:07:00 【给我一瓶冰阔洛】
条件等待和互斥锁有不同,互斥锁是不同协程公用一个锁,条件等待是不同协程各用一个锁,但
是wait()方法调用会等待(阻塞),直到有信号发过来,不同协程是共用信号。
Wait() 阻塞当前协成
func (c *Cond) Wait() {
c.checker.check()
t := runtime_notifyListAdd(&c.notify) // 等待的goruntine数+1
c.L.Unlock() // 释放锁资源
runtime_notifyListWait(&c.notify, t) // 阻塞,等待其他goruntine唤醒
c.L.Lock() // 获取资源
}Signa() 和 BroadCast() 唤醒协成
func (c *Cond) Signal() {
c.checker.check()
runtime_notifyListNotifyOne(&c.notify) // 唤醒最早被阻塞的goruntine
}
func (c *Cond) Broadcast() {
c.checker.check()
runtime_notifyListNotifyAll(&c.notify) // 唤醒所有goruntine
}demo
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var cond sync.Cond
//生产者
func producer(out chan<- int, index int){
for{
cond.L.Lock()
for len(out) == 10 {
fmt.Println(index, "len == 10")
cond.Wait()//阻塞 等待
}
num := rand.Intn(800)
time.Sleep(time.Second)
out<- num
fmt.Println("生产者:",index, num)
cond.L.Unlock()
cond.Signal()//唤醒阻塞的协程
}
}
//消费者
func consumer(in <-chan int, index int){
for{
cond.L.Lock()
for len(in) == 0 {
fmt.Println(index, "len == 0")
cond.Wait()//阻塞 等待
}
time.Sleep(time.Second)
num := <-in
fmt.Println("消费者:",index,num)
cond.L.Unlock()
cond.Signal()//唤醒阻塞的协程
}
}
func main() {
ch := make(chan int, 10)
rand.Seed(time.Now().UnixMilli())
cond.L = new(sync.Mutex)
for i:=1; i<=4; i++{
go producer(ch, i)
}
for i:=1; i<=6; i++{
go consumer(ch, i)
}
quit := make(chan []struct{})
<-quit
}
边栏推荐
- wait解决僵尸进程
- [LeetCode] 回文数【9】
- [LeetCode] 存在重复元素【217】
- [shutter] shutter gesture interaction (small ball following the movement of fingers)
- Notes on key vocabulary of the original English book biography of jobs (IX) [chapter seven]
- JS solution for obtaining the width and height of hidden elements whose display is none
- Micro service gateway selection, please accept my knees!
- [LeetCode] 反转字符串中的单词 III【557】
- 世界环境日 | 周大福用心服务推动减碳环保
- UE4 game architecture learning notes
猜你喜欢
随机推荐
I admire that someone explained such an obscure subject as advanced mathematics so easily
Get off work on time! Episode 6 of Excel Collection - how to split and count document amounts
百度智能云-创建人脸识别应用
牛客网:龙与地下城游戏
UE4 游戏架构 学习笔记
服务器响应状态码
Niuke: Dragon and dungeon games
NC24325 [USACO 2012 Mar S]Flowerpot
存储单位换算
Market Research - current market situation and future development trend of aircraft audio control panel system
uniapp微信登录返显用户名和头像
wait解决僵尸进程
Introduction to database system Chapter 1 short answer questions - how was the final exam?
Developers share | HLS and skillfully use Axi_ Customize the master bus interface instructions and improve the data bandwidth - area exchange speed
Perceptron model and Application
小鹏P7出事故,安全气囊未弹出,这正常吗?
Simpleitk use - 3 Common operations
php优化foreach中的sql查询
Golang的学习路线
PHP微信抢红包的算法









