当前位置:网站首页>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 ~
边栏推荐
- Flask application case
- xpath
- [LeetCode]30. Concatenate substrings of all words
- The create database of gbase 8A takes a long time to query and is suspected to be stuck
- Professor of Tsinghua University: software testing has gone into a misunderstanding - "code is necessary"
- Typescript learning
- How to do function test well? Are you sure you don't want to know?
- [LeetCode]515. Find the maximum value in each tree row
- Stm32cubeide1.9.0\stm32cubemx 6.5 f429igt6 plus lan8720a, configure eth+lwip
- A method of go accessing gbase 8A database
猜你喜欢

I think I should start writing my own blog.

登录凭证(cookie+session和Token令牌)

. Net learning notes (V) -- lambda, LINQ, anonymous class (VaR), extension method

Interval DP of Changyou dynamic programming
![[MySQL] database function clearance Tutorial Part 2 (window function topic)](/img/03/2b37e63d0d482d5020b7421ac974cb.jpg)
[MySQL] database function clearance Tutorial Part 2 (window function topic)

CUDA error:out of memory caused by insufficient video memory of 6G graphics card

Do280openshift access control -- Security Policy and chapter experiment

The "business and Application Security Development Forum" held by the ICT Institute was re recognized for the security capability of Tianyi cloud

YOLOv6:又快又准的目标检测框架开源啦

Go from introduction to practice - error mechanism (note)
随机推荐
Yarn performance tuning of CDH cluster
crontab定时任务常用命令
This set of steps for performance testing using JMeter includes two salary increases and one promotion
Typescript learning
Example of using gbase 8A OLAP function group by grouping sets
如何做好功能测试?你确定不想知道吗?
Solution to the error of VMware tool plug-in installed in Windows 8.1 system
不外泄的测试用例设计秘籍--模块测试
渗透学习-sql注入过程中遇到的问题-针对sort=left(version(),1)的解释-对order by后接字符串的理解
xpath
QT base64 encryption and decryption
深度学习又有新坑了!悉尼大学提出全新跨模态任务,用文本指导图像进行抠图
Interval DP of Changyou dynamic programming
Introduction to ARCS Model
Go from introduction to practice - error mechanism (note)
mysql 大于 小于 等于符号的表示方法
YOLOv6:又快又准的目标检测框架开源啦
gomock mockgen : unknown embedded interface
\w和[A-Za-z0-9_],\d和[0-9]等价吗?
QT large file generation MD5 check code