Go study notes -- sync.Cond condition variable

Introduction

  sync.Cond is a condition variable based on mutex/read-write lock, which is used to coordinate those Goroutines that want to access shared resources . When the state of a shared resource changes, sync.Cond can be used to notify Goroutines that are blocked waiting for the condition to occur .

Relationship to Mutex

  First of all, condition variables are implemented based on mutexes/read-write locks, and the initialization of condition variables is inseparable from mutexes.
  Second, the purpose of mutexes is to protect critical sections and shared resources, while condition variables are used to coordinate coroutines that want to access these shared resources.

scenes to be used

I can use condition variables for producer consumer scenarios etc.
as follows:

import (
	"fmt"
	"sync"
	"time"
)

var stage = 0
var lock sync.Mutex
var pCond = sync.NewCond(&lock) //等待生产的条件变量
var cCond = sync.NewCond(&lock) //等待消费的条件变量

func produce() {
    
    
	pCond.L.Lock() //先获取条件变量中的锁
	defer pCond.L.Unlock()//使用defer函数在方法执行完之后解锁
	for stage == 1 {
    
     //使用 for 判断当前条件是否需要等待,避免假唤醒,当有商品时,不生产。
		pCond.Wait()//等待商品被消费后的通知
	}
	//正常生产商品
	stage = 1
	fmt.Println("生产成功")
	//通知消费者消费
	cCond.Signal()//唤醒最靠前的一个协程
}

func consume() {
    
    
	cCond.L.Lock()
	for stage == 0 {
    
    
		cCond.Wait()
	}
	//正常消费商品
	stage = 0
	fmt.Println("消费成功")
	cCond.L.Unlock()
	//通知生产者生产
	pCond.Signal() 
}

func main() {
    
    
	count := 5
	for i := 0; i < count; i++ {
    
    
		go consume()
		go produce()
	}
	time.Sleep(time.Millisecond * 1000)
}
----------------------------------
生产成功
消费成功
生产成功
消费成功
生产成功
消费成功
生产成功
消费成功
生产成功
消费成功

The difference between Signal and Boardcast

First, cond.Wait() will add the current coroutine to the end of the notification queue. When using Signal to wake up the waiting coroutine, only the coroutine at the head of the queue can be woken up.
Using Boardcast will wake up all waiting coroutines.

Precautions

  1. The Wait method needs to be executed under the protection of the mutex it is based on, otherwise it will cause an unrecoverable panic , so we need to acquire the mutex it is based on before calling this method.
  2. The Signal and Boardcast methods don't need to be protected by a mutex, and it's best not to call them before unlocking the mutex.

Guess you like

Origin blog.csdn.net/qq_40096897/article/details/128441774