当前位置:网站首页>go channel && select
go channel && select
2022-06-30 14:09:00 【Zhen Jie.】
channel brief introduction
goroutine yes Go An important mechanism for implementing concurrency in ,channel yes goroutine An important bridge for communication between .channel It's a kind of go A secure message queue used by a process to receive or send messages ,channel It's like two go The catheter between the processes , To synchronize resources .
Reputation creation channel There are two common ways ,
// The way 1: Use make establish ( The data type it passes must be defined )
ch :make(chan int, 2) // Create buffer channels
ch :make(chan int) // Create unbuffered channels
ch :make(chan string, 0) // Create unbuffered channels
// The way 2: Use it directly var Statement
var ch chan int
buffer channel And unbuffering channel
buffer channel: Have buffer , When the buffer is full , The sender will jam ; When the buffer is empty , The recipient will jam .
Simple use example , as follows
func main() {
ch := make(chan int, 1) // Create a type of int, The buffer size is 1 Of channel
ch <- 2 // take 2 Send to ch
n, ok := <- ch // n Receive from ch The value of the emission
if ok {
fmt.Println(n) // Output :2
}
close(ch) // close channel
}
Use channel Points for attention :
- To an already close fall Of channel Send a message , Will trigger panic;
- It is not allowed to report to the closed channel Send a message , But you can continue channel receive messages ;
- To one nil Of channel Send a message , It's going to keep clogging up ;
- When channel closed And channel The cache is empty when , Continue from channel Receiving a message will get a zero value of the corresponding type .
Non buffering channel: The buffer size is 0 Of channel, such channel The recipient of will block until the message is received , The sender will block until the receiver receives the message , This mechanism can be used for two goroutine State synchronization .
A simple example :main In the function goroutine, Through the use of unbuffered queues , To be able to guarantee that goroutine Before the end of execution main The function does not exit prematurely , as follows :
func worker(done chan bool){
fmt.Println("start working...")
done <- true
fmt.Println("end working...")
}
func main() {
done := make(chan bool, 1)
go worker(done)
<- done
}
select brief introduction
select Dedicated to channel send and receive operations , Looks like switch Very similar , But the methods of choice and judgment are completely different .
In the following example , adopt select Use , To ensure the worker The transaction in can be executed before exiting main function
func strWorker(ch chan string) {
time.Sleep(1 * time.Second)
fmt.Println("do something with strWorker...")
ch <- "str"
}
func intWorker(ch chan int) {
time.Sleep(2 * time.Second)
fmt.Println("do something with intWorker...")
ch <- 1
}
func main() {
chStr := make(chan string)
chInt := make(chan int)
go strWorker(chStr)
go intWorker(chInt)
for i := 0; i < 2; i++ {
select {
case <-chStr:
fmt.Println("get value from strWorker")
case <-chInt:
fmt.Println("get value from intWorker")
}
}
}
边栏推荐
- Loss function: Diou loss handwriting implementation
- [KALI] KALI系统、软件更新(附带镜像源)
- What is erdma as illustrated by Coptic cartoon?
- Realize a simple LAN communication (similar to feiqiu)
- Unity animator parameter
- 深入理解.Net中的线程同步之构造模式(二)内核模式2.内核模式构造物Semaphone
- 表格储存中sql查询的时候,查询结果增加主键报错,查询结果超过10w行。需要对主键增加上多元索引吗?
- Jetpack Compose 实现完美屏幕适配
- Simple understanding of the difference between get request and post submission
- numpy 创建空数组 data = np.empty(shape=[1, 64,64,3])
猜你喜欢

Step by step | help you easily submit Google play data security form

【Redis 系列】redis 学习十六,redis 字典(map) 及其核心编码结构

Observable, seulement fiable: première bombe de salon de la série cloudops d'exploitation et d'entretien automatisés dans le nuage
![[Title brushing] avoid flooding](/img/2d/95498d54c0c3c5ca79bb72b7a977bc.png)
[Title brushing] avoid flooding

MFQE 2.0: A New Approach for Multi-FrameQuality Enhancement on Compressed Video

This article explains the concepts of typed array, arraybuffer, typedarray, DataView, etc
![[Title brushing] coco, who likes bananas](/img/66/5646ac7e644025ccaee7c17f62ce17.png)
[Title brushing] coco, who likes bananas

用Unity实现Flat Shading

Flat shading with unity

Waving flags and shouting for basic language
随机推荐
Embedded development: five C features that may no longer be prohibited
numpy 创建空数组 data = np.empty(shape=[1, 64,64,3])
数据库表为什么写不进数据了
[the path of system analyst] Chapter V software engineering (software process improvement)
Comprehensively analyze the basic features and summary of free and paid SSH tools
步骤详解 | 助您轻松提交 Google Play 数据安全表单
Waving flags and shouting for basic language
IM即时通讯应用开发中无法解决的“顽疾”
[Title brushing] avoid flooding
想请教一下,我在佛山,到哪里开户比较好?手机开户是安全么?
"As a service", the inevitable choice of enterprise digital transformation
Deep understanding Net (2) kernel mode 3 Kernel mode construct mutex
Getting started with shell Basics
第四批入围企业公示——年度TOP100智能网联供应商评选
【科研数据处理】[实践]类别变量频数分析图表、数值变量分布图表与正态性检验(包含对数正态)
LeetCode_ Stack_ Medium_ 227. basic calculator II (without brackets)
Service online governance
这个编辑器即将开源!
DNS resolution home network access public DNS practice
【Kubernetes系列】K8s设置MySQL8大小写不敏感