当前位置:网站首页>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
}
边栏推荐
- Il n'est pas nécessaire d'appuyer longtemps sur la fonction de démarrage pour modifier Jelly [chapitre]
- How can I use knockout's $parent/$root pseudovariables from inside a . computed() observable?
- 手写ORM(对象关系映射)增删改查
- PHP wechat red packet grabbing algorithm
- NC24325 [USACO 2012 Mar S]Flowerpot
- Source code analysis - lightweight asynchronous crawler framework Ruia
- phpcms实现订单直接支付宝支付功能
- New feature of go1.18: trylock, which has been tossed n times
- Market Research - current market situation and future development trend of third-party data platform
- Using rendertext() to output multiple lines of text with rendertext() in R shiny
猜你喜欢

Struct, bit segment, enumeration, union

Task and privilege level protection

SimpleITK使用——4. 奇怪的问题

wait解决僵尸进程

Niuke: Dragon and dungeon games

性能优化----严苛模式

手写ORM(对象关系映射)增删改查

【ODX Studio编辑PDX】-0.1-如何快速查看各Variant变体间的支持的诊断信息差异(服务,Sub-Function...)
![[shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)](/img/07/6f2dfb543cb0ab4f27169da7e6ad07.jpg)
[shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)

UE4 游戏架构 学习笔记
随机推荐
牛客网:最大子矩阵
【ODX Studio编辑PDX】-0.1-如何快速查看各Variant变体间的支持的诊断信息差异(服务,Sub-Function...)
[QT] Q multithreaded development - Analysis of multithreaded application examples (Mandelbrot)
Radis:Linux上安装Redis(步骤)
小鹏P7出事故,安全气囊未弹出,这正常吗?
[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)
[LeetCode] 回文数【9】
[QT] QT multithreading development - four methods to realize multithreading design
Dynamic memory allocation (malloc calloc realloc free)
《乔布斯传》英文原著重点词汇笔记(九)【 chapter seven】
Unity发布WebGL播放声音的一种方法
Leetcode circular linked list (fast and slow pointer) code line by line interpretation
Commodity information management system (C language document version)
Market Research - current market situation and future development trend of handheld wound imaging equipment
影视随摘
Source code analysis - lightweight asynchronous crawler framework Ruia
Market Research - current market situation and future development trend of night vision goggles for pilots
[error record] the flutter reports an error (could not read script 'xxx\flutter\u tools\gradle\app\u plugin\u loader.gradle')
It's not easy to say I love you | use the minimum web API to upload files (swagger support) # yyds dry inventory #
Utilisation de simpletk - 4. Question étrange