当前位置:网站首页>Learn to go concurrent programming in 7 days go language sync Application and implementation of cond
Learn to go concurrent programming in 7 days go language sync Application and implementation of cond
2022-06-27 22:27:00 【Sledgehammer love programming】
List of articles
Catalog
3.Sync.Cond Of BroadCast Methods use
4.Sync.Cond Of Signal() Methods use
3、 ... and 、Cond Internal principle
Preface
The previous programming articles mainly introduced some principles and applications of concurrent programming , It mainly solves the problem of critical resource protection in concurrent programming 、 Communication problems between multithreads 、 Multithread execution order problem . But in actual programming , A common problem encountered is conditional execution between multiple threads . Conditional execution between multiple threads means that multiple threads are in a waiting state , After receiving the corresponding signal, execute . Take a living scene : Many people queue up for the bus , Everyone is ready to get on the bus , But the car hasn't come yet . Only wait , Looking forward to the stars , Looking forward to the moon , Here comes the bus . When the bus comes , For people waiting in line , There will be two situations :1、 Successfully get on the bus 2、 Because there are so many people , vehicle Refuse to carry , No seats in row . In this case , The waiting condition is on the bus , And give instructions on how many people to take on the train .

One 、sync.Cond What is it?
sync.Cond be located sync.package The package , The main function is to provide a temporary variable . Through this temporary variable, when the waiting condition is not satisfied , Thread blocking 、 Wait until the conditions are met , The function of thread re execution .
Two 、sync.Cond Use
1. Sync.Cond initialization
Cond During initialization , Need to pass in a Mutex Parameters of type .
package main
import "sync"
func main() {
mutex := sync.Mutex{}
cond := sync.NewCond(&mutex)
}
2.Sync.Cond Easy to use
Here is a simple implementation Cond Use , The implementation starts with go Thread waiting , Thread blocking waits until cond.BroadCast perform , To wake up the waiting thread .
package main
import (
"fmt"
"sync"
"time"
)
func main() {
signal := 1
mutex := sync.Mutex{}
cond := sync.NewCond(&mutex)
go func() {
cond.L.Lock()
for signal == 1 {
fmt.Println(" Thread starts waiting ")
cond.Wait()
fmt.Println(" Thread waiting to end ")
}
cond.L.Unlock()
}()
time.Sleep(200*time.Millisecond)
cond.Broadcast()
signal=0
time.Sleep(200*time.Millisecond)
}
3.Sync.Cond Of BroadCast Methods use
The following implements a BroadCast application , Realization 10 Threads blocking and waiting at the same time , Conditional variables execute BroadCase after , All threads execute concurrently . Because it uses BroadCast Methods , Wake up all waiting threads , So use waitGroup Manage batch thread execution .
package main
import (
"fmt"
"sync"
"time"
)
func main() {
signal := 1
mutex := sync.Mutex{}
cond := sync.NewCond(&mutex)
group := sync.WaitGroup{}
group.Add(10)
for i := 0; i < 10; i++ {
go func(int1 int) {
defer group.Done()
cond.L.Lock()
for signal == 1 {
fmt.Printf(" Threads %d Start the waiting \n",int1)
cond.Wait()
fmt.Printf(" Threads %d end \n",int1)
}
cond.L.Unlock()
}(i)
}
time.Sleep(200*time.Millisecond)
cond.Broadcast()
signal=0
group.Wait()
}
Corresponding execution effect :
Threads 4 Start the waiting
Threads 9 Start the waiting
Threads 5 Start the waiting
Threads 6 Start the waiting
Threads 7 Start the waiting
Threads 8 Start the waiting
Threads 1 Start the waiting
Threads 0 Start the waiting
Threads 2 Start the waiting
Threads 3 Start the waiting
Threads 3 end
Threads 2 end
Threads 7 end
Threads 4 end
Threads 9 end
Threads 5 end
Threads 6 end
Threads 1 end
Threads 0 end
Threads 8 endProcess finished with the exit code 0
4.Sync.Cond Of Signal() Methods use
The following implements a BroadCast application , Realization 10 Threads blocking and waiting at the same time , Conditional variables execute Signal after , Concurrent preemption of all threads . Because it uses Signal Methods , Only one thread will be executed . The rule of choice is "first come, first served, first served" , Who will be the first to execute .
package main
import (
"fmt"
"sync"
"time"
)
func main() {
signal := 1
mutex := sync.Mutex{}
cond := sync.NewCond(&mutex)
c := make(chan struct{}, 1)
for i := 0; i < 10; i++ {
go func(int1 int) {
defer func() {
c<- struct{}{}
}()
cond.L.Lock()
for signal == 1 {
fmt.Printf(" Threads %d Start the waiting \n",int1)
cond.Wait()
fmt.Printf(" Threads %d end \n",int1)
}
cond.L.Unlock()
}(i)
}
time.Sleep(200*time.Millisecond)
cond.Signal()
signal=0
<-c
}
Corresponding execution effect :
Threads 0 Start the waiting
Threads 9 Start the waiting
Threads 2 Start the waiting
Threads 3 Start the waiting
Threads 4 Start the waiting
Threads 5 Start the waiting
Threads 6 Start the waiting
Threads 7 Start the waiting
Threads 8 Start the waiting
Threads 1 Start the waiting
Threads 0 end
3、 ... and 、Cond Internal principle
The core source code is as follows :
func (c *Cond) Wait() {
c.checker.check()
t := runtime_notifyListAdd(&c.notify) // Add thread to wait queue
c.L.Unlock()
runtime_notifyListWait(&c.notify, t) // Let the thread waiting on the queue start waiting
c.L.Lock()
}
summary
That's what we're going to talk about today , This article only briefly introduces cond Use ,Cond It provides a mechanism that can realize multi-threaded cooperative execution . This mechanism has been applied to many projects , Some related content will be updated in the future .
You are welcome to give us more valuable comments , Leave more messages and interact ~
边栏推荐
- 关于davwa的SQL注入时报错:Illegal mix of collations for operation ‘UNION‘原因剖析与验证
- How to prioritize the contents in the queue every second
- \W and [a-za-z0-9_], \Are D and [0-9] equivalent?
- Educational Codeforces Round 108 (Rated for Div. 2)
- Codeforces Round #716 (Div. 2)
- 爬虫笔记(1)- urllib
- Typescript learning
- [leetcode] dynamic programming solution split integer i[silver fox]
- BAT测试专家对web测试和APP测试的总结
- Day8 - cloud information project introduction and creation
猜你喜欢
![[MySQL] database function clearance Tutorial Part 2 (window function topic)](/img/03/2b37e63d0d482d5020b7421ac974cb.jpg)
[MySQL] database function clearance Tutorial Part 2 (window function topic)

关于davwa的SQL注入时报错:Illegal mix of collations for operation ‘UNION‘原因剖析与验证

【MySQL】数据库函数通关教程下篇(窗口函数专题)

爬虫笔记(1)- urllib

VMware virtual machine PE startup

Codeforces Round #719 (Div. 3)
Conversion between flat array and JSON tree

Go from introduction to practice - error mechanism (note)

Management system itclub (Part 2)

百万年薪独家专访,开发人员不修复bug怎么办?
随机推荐
[LeetCode]30. Concatenate substrings of all words
[LeetCode]508. 出現次數最多的子樹元素和
\w和[A-Za-z0-9_],\d和[0-9]等价吗?
average-population-of-each-continent
Secret script of test case design without leakage -- module test
PCIe knowledge point -008: structure of PCIe switch
The create database of gbase 8A takes a long time to query and is suspected to be stuck
Record a list object traversal and determine the size of the float type
Experience sharing of meituan 20K Software Test Engineers
Typescript learning
年薪50W+的测试大鸟都在用这个:Jmeter 脚本开发之——扩展函数
[leetcode] dynamic programming solution split integer i[silver fox]
Gbase 8A method for reducing the impact on the system by controlling resource usage through concurrency during node replacement of V8 version
《7天学会Go并发编程》第六天 go语言Sync.cond的应用和实现 go实现多线程联合执行
. Net learning notes (V) -- lambda, LINQ, anonymous class (VaR), extension method
Acwing weekly contest 57- digital operation - (thinking + decomposition of prime factor)
Professor of Tsinghua University: software testing has gone into a misunderstanding - "code is necessary"
【mysql实战】查询语句实战演示
使用Fiddler模拟弱网测试(2G/3G)
01 golang environment construction