浅谈Golang广播sync.Cond

前言

  1. sync.Cond的核心实现 - 通过一个锁,封装了notify 通知的实现,包括了单个通知与广播这两种方式
  2. sync.Cond与channel的异同 - channel应用于一收一发的场景,sync.Cond应用于多收一发的场景

代码

package main

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

// 示例来自https://stackoverflow.com/questions/36857167/how-to-correctly-use-sync-cond
//fatal error: all goroutines are asleep - deadlock!
//goroutine 1 [sync.Cond.Wait]:
因为c.Wait()里面加锁,而外面没有解锁,造成死锁
func syncCondErr() {
	m := sync.Mutex{}
	c := sync.NewCond(&m)
	go func() {
		time.Sleep(1 * time.Second)
		c.Broadcast()
	}()
	m.Lock()
	time.Sleep(2 * time.Second)
	c.Wait()
}
//Tip:正确使用方式
func syncCondExplain() {
	m := sync.Mutex{}
	c := sync.NewCond(&m)

	// Tip: 主协程先获得锁
	c.L.Lock()
	go func() {
		// Tip: 协程一开始无法获得锁
		c.L.Lock()
		defer c.L.Unlock()
		fmt.Println("3. 该协程获得了锁")
		time.Sleep(2 * time.Second)
		// Tip: 通过notify进行广播通知,cond.Signal()用于随机一个单播
		c.Broadcast()
		fmt.Println("4. 该协程执行完毕,即将执行defer中的解锁操作")
	}()
	fmt.Println("1. 主协程获得锁")
	time.Sleep(1 * time.Second)
	fmt.Println("2. 主协程依旧抢占着锁获得锁")
	// Tip: 看一下Wait的大致实现,可以了解到,它是先释放锁,阻塞等待,直到收到了notify,又进行加锁
	c.Wait()
	// Tip: 记得释放锁
	c.L.Unlock()
	fmt.Println("Done")
}
//Tip:例子
func syncCond() {
	lock := sync.Mutex{}
	cond := sync.NewCond(&lock)

	for i := 0; i < 5; i++ {
		go func(i int) {
			cond.L.Lock()
			defer cond.L.Unlock()
			cond.Wait()
			fmt.Printf("No.%d Goroutine Receive\n", i)
		}(i)
	}
	time.Sleep(time.Second)
	cond.Broadcast()
	//cond.Signal()
	time.Sleep(time.Second)
}

源码分析

//Tip:wait先解锁,阻塞等待notify,得到后再加锁
func (c *Cond) Wait() {
	c.checker.check()
	t := runtime_notifyListAdd(&c.notify)
	c.L.Unlock()
	runtime_notifyListWait(&c.notify, t)
	c.L.Lock()
}
//广播
func (c *Cond) Broadcast() {
	c.checker.check()
	runtime_notifyListNotifyAll(&c.notify)
}
// notifyListNotifyAll notifies all entries in the list.
//go:linkname notifyListNotifyAll sync.runtime_notifyListNotifyAll
func notifyListNotifyAll(l *notifyList) {
	// Go through the local list and ready all waiters.
	for s != nil {
		next := s.next
		s.next = nil
		readyWithTime(s, 4)
		s = next
	}
}
//单播
func (c *Cond) Signal() {
	c.checker.check()
	runtime_notifyListNotifyOne(&c.notify)
}
// notifyListNotifyOne notifies one entry in the list.
//go:linkname notifyListNotifyOne sync.runtime_notifyListNotifyOne
func notifyListNotifyOne(l *notifyList) {
	for p, s := (*sudog)(nil), l.head; s != nil; p, s = s, s.next {
		if s.ticket == t {
			n := s.next
			if p != nil {
				p.next = n
			} else {
				l.head = n
			}
			if n == nil {
				l.tail = p
			}
			unlock(&l.lock)
			s.next = nil
			readyWithTime(s, 4)
			return
		}
	}
	unlock(&l.lock)
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cheems~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值