当前位置:网站首页>GO 使用channel进行同步 (缓冲channel)
GO 使用channel进行同步 (缓冲channel)
2022-04-21 10:42:00 【genispan】
上一篇文章提到了普通的channel用来进行线程的同步。Go语言里面还有一种缓冲式的channel。
ch := make(chan int, 100)
需要执行类型和缓冲区的大小。
package main
import "fmt"
func main() {
c := make(chan int, 2) //建立int类型大小为2的缓冲区
c <- 1 //缓冲区1赋值为1
c <- 2 //缓冲区2赋值为2
fmt.Println(<-c) //输出缓冲区1
fmt.Println(<-c) //输出缓冲区2
}
可以循环 for i := range c 来不断从 channel 接收值,直到它被关闭。
package main
import (
"fmt"
)
func fibonacci(n int, c chan int) {
x, y := 1, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c)+2, c)
for i := range c {
fmt.Println(i)
}
}
版权声明
本文为[genispan]所创,转载请带上原文链接,感谢
https://blog.csdn.net/genispan/article/details/43458375
边栏推荐
- Summary of knapsack problem (0-1, complete, multiple knapsack problem)
- openCV——轮廓检测
- torch. autograd. Function customization
- Where is London gold safe to open an account?
- Can Jingdong Logistics, ririshun supply chain and Shunfeng find the optimal solution of logistics under the "epidemic"?
- Usage of SAP ABAP for all entries
- Map与JsonObject区别
- 微信公众号网页分享设置及问题
- Postman setting environment variables is simple and practical
- 如何阅读一份源代码?
猜你喜欢

如何阅读一份源代码?

Vulnhub PRIME: 1

Enter the welcome interface when idea and pycharm are started

pip install的时候出现问题,无法连接...(pip配置镜像源)

"Air washing" meets the iteration again, and the imitator has a new goal

AcWing 1761. 阻挡广告牌 (计算几何,两个矩形的交集)

Usage of SAP ABAP for all entries

Pytorch梯度检查 torch.autograd.gradcheck

桶排序 ← C语言实现

NFT中的版权漏洞:产品设计需考虑法律层面
随机推荐
Nanny level tutorial on building personal home page (I)
Talk about your GC tuning ideas?
塔米狗企业并购平台上,法律服务商名单目录!
Design a high-quality API interface
What is the future development prospect of automated operation and maintenance platform?
【WCN685x】如何判断wifi驱动调用的bdwlan文件是哪个?
C语言中使用scanf函数时应注意的问题
Construction of mobile communication platform (voice visual screen, sending and receiving SMS)
Pytorch学习笔记(2)一元线性回归、计算图示例
Vulnhub PRIME: 1
微信公众号网页分享设置及问题
趣丸集团招股书“失效”,旗下TT语音已下架,如何实现稳定增长?
摩尔线程与Ampere Computing达成合作
[pytorch] 1-to-many IOU calculation skills
两两数之和
The most easy to understand dependency injection and control inversion
openCV——轮廓检测
泛型note
Alibaba cloud mobile R & D platform EMAS, product dynamics in March
京东物流、日日顺供应链、顺丰们能否在“疫”下找到物流的最优解?