脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - Go语言中sync.Cond使用详解

Go语言中sync.Cond使用详解

2021-09-18 00:51banjming Golang

本文主要介绍了Go语言中sync.Cond使用详解,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

sync.Cond 可以用来干什么?

Golang 的 sync 包中的 Cond 实现了一种条件变量,可以使用多个 Reader 等待公共资源。

每个 Cond 都会关联一个 Lock ,当修改条件或者调用 Wait 方法,必须加锁,保护 Condition。 有点类似 Java 中的 Wait 和 NotifyAll。

sync.Cond 条件变量是用来协调想要共享资源的那些 goroutine, 当共享资源的状态发生变化时,可以被用来通知被互斥锁阻塞的 gorountine。

与 Sync.Mutex 的区别

sync.Cond 基于互斥锁,和互斥锁有什么区别?

sync.Mutex 通常用来保护临界区和共享资源,条件变量 sync.Cond 用来协调想要访问的共享资源。

sync.Cond 使用场景

有一个协程正在接收数据,其他协程必须等待这个协程接收完数据,才能读取到正确的数据。

上述情形下,如果单纯的使用 channel 或者互斥锁,只能有一个协程可以等待,并读取到数据,没办法通知其他协程也读取数据。

这个时候怎么办?

  • 可以用一个全局变量标识第一个协程是否接收数据完毕,剩下的协程反复检查该变量的值,直到读取到数据。
  • 也可创建多个 channel, 每个协程阻塞在一个 Channel 上,由接收数据的协程在数据接收完毕后,挨个通知。

然后 Go 中其实内置来一个 sync.Cond 来解决这个问题。

sync.Cond

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Each Cond has an associated Locker L (often a *Mutex or *RWMutex),
// which must be held when changing the condition and
// when calling the Wait method.
//
// A Cond must not be copied after first use.
type Cond struct {
        noCopy noCopy
 
        // L is held while observing or changing the condition
        L Locker
 
        notify  notifyList
        checker copyChecker
}

可以看到每个 Cond 都会关联一个 锁 L (互斥锁 Mutex, 或者读写锁 * RMMutex), 当修改条件或者使用 Wait 的时候必须要加锁。

sync.Cond 有哪些方法

NewCond 创建实例

?
1
func NewCond(l Locker) *Cond

NewCond 创建实例需要关联一个锁。

具体实例:

?
1
cadence := sync.NewCond(&sync.Mutex{})

Broadcast 广播唤醒所有

?
1
2
3
4
5
// Broadcast wakes all goroutines waiting on c.
//
// It is allowed but not required for the caller to hold c.L
// during the call.
func (c *Cond) Broadcast()

Broadcast 唤醒所有等待条件变量 c 的 goroutine,无需锁保护。

具体实例:

?
1
2
3
4
5
go func() {
   for range time.Tick(1 * time.Millisecond) {
      cadence.Broadcast()
   }
}()

Signal 唤醒一个协程

?
1
2
3
4
5
// Signal wakes one goroutine waiting on c, if there is any.
//
// It is allowed but not required for the caller to hold c.L
// during the call.
func (c *Cond) Signal()

Signal 只唤醒任意1个等待条件变量 c 的 goroutine,无需锁保护。 有点类似 Java 中的 Notify

Wait 等待

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Wait atomically unlocks c.L and suspends execution
// of the calling goroutine. After later resuming execution,
// Wait locks c.L before returning. Unlike in other systems,
// Wait cannot return unless awoken by Broadcast or Signal.
//
// Because c.L is not locked when Wait first resumes, the caller
// typically cannot assume that the condition is true when
// Wait returns. Instead, the caller should Wait in a loop:
//
//    c.L.Lock()
//    for !condition() {
//        c.Wait()
//    }
//    ... make use of condition ...
//    c.L.Unlock()
//
func (c *Cond) Wait()

调用 Wait 会自动释放锁 c.L,并挂起调用者所在的 goroutine,因此当前协程会阻塞在 Wait 方法调用的地方。如果其他协程调用了 Signal 或 Broadcast 唤醒了该协程,Wait 方法结束阻塞时,并重新给 c.L 加锁,并且继续执行 Wait 后面的代码

代码示例:

?
1
2
3
4
5
6
c.L.Lock()
for !condition() {
    c.Wait()
}
... make use of condition ...
c.L.Unlock()

代码示例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package sync
 
import (
   "log"
   "sync"
   "testing"
   "time"
)
 
var done = false
 
func read(name string, c *sync.Cond) {
   c.L.Lock()
   for !done {
      c.Wait()
   }
   log.Println(name, "starts reading")
   c.L.Unlock()
}
 
func write(name string, c *sync.Cond) {
   log.Println(name, "starts writing")
   time.Sleep(time.Second)
   c.L.Lock()
   done = true
   c.L.Unlock()
   log.Println(name, "wakes all")
   c.Broadcast()
}
 
func TestSyncCond(t *testing.T) {
   cond := sync.NewCond(&sync.Mutex{})
 
   go read("reader1", cond)
   go read("reader2", cond)
   go read("reader3", cond)
   write("writer", cond)
 
   time.Sleep(time.Second * 3)
}

运行结果

=== RUN   TestSyncCond
2021/08/26 11:06:48 writer starts writing
2021/08/26 11:06:49 writer wakes all
2021/08/26 11:06:49 reader3 starts reading
2021/08/26 11:06:49 reader2 starts reading
2021/08/26 11:06:49 reader1 starts reading
--- PASS: TestSyncCond (4.01s)
PASS

到此这篇关于Go语言中sync.Cond使用详解的文章就介绍到这了,更多相关Go sync.Cond内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://juejin.cn/post/7000570207185944589

延伸 · 阅读

精彩推荐
  • Golang深入浅析Go中三个点(...)用法

    深入浅析Go中三个点(...)用法

    这篇文章主要介绍了深入浅析Go中三个点(...)用法,需要的朋友可以参考下...

    踏雪无痕SS6472021-11-17
  • GolangGo语言range关键字循环时的坑

    Go语言range关键字循环时的坑

    今天小编就为大家分享一篇关于Go语言range关键字循环时的坑,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来...

    benben_20154202020-05-23
  • GolangGo语言实现自动填写古诗词实例代码

    Go语言实现自动填写古诗词实例代码

    这篇文章主要给大家介绍了关于Go语言实现自动填写古诗词的相关资料,这是最近在项目中遇到的一个需求,文中通过示例代码介绍的非常详细,需要的朋...

    FengY5862020-05-14
  • Golanggo语言获取系统盘符的方法

    go语言获取系统盘符的方法

    这篇文章主要介绍了go语言获取系统盘符的方法,涉及Go语言调用winapi获取系统硬件信息的技巧,具有一定参考借鉴价值,需要的朋友可以参考下 ...

    无尽海3862020-04-24
  • GolangGolang实现四种负载均衡的算法(随机,轮询等)

    Golang实现四种负载均衡的算法(随机,轮询等)

    本文介绍了示例介绍了Golang 负载均衡的四种实现,主要包括了随机,轮询,加权轮询负载,一致性hash,感兴趣的小伙伴们可以参考一下...

    Gundy_8442021-08-09
  • GolangGo语言基础单元测试与性能测试示例详解

    Go语言基础单元测试与性能测试示例详解

    这篇文章主要为大家介绍了Go语言基础单元测试与性能测试示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助祝大家多多进步...

    枫少文7812021-12-05
  • GolangGolang 语言极简类型转换库cast的使用详解

    Golang 语言极简类型转换库cast的使用详解

    本文我们通过 cast.ToString() 函数的使用,简单介绍了cast 的使用方法,除此之外,它还支持很多其他类型,在这没有多多介绍,对Golang 类型转换库 cast相关知...

    Golang语言开发栈6112021-12-02
  • GolangGO语言字符串处理Strings包的函数使用示例讲解

    GO语言字符串处理Strings包的函数使用示例讲解

    这篇文章主要为大家介绍了GO语言字符串处理Strings包的函数使用示例讲解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加...

    Jeff的技术栈6882022-04-14