golang中的channel
2016-06-27 22:31
495 查看
代码如下:
// fuck.go
package main
import (
"fmt"
)
func Count(ch chan int) {
fmt.Printf("Counting")
ch <- 1
}
func main() {
chs := make([]chan int, 10)
for i := 0; i < 10; i++ {
chs[i] = make(chan int)
go Count(chs[i])
}
for _, ch := range chs {
fmt.Printf("\n")
fmt.Print(<-ch)
}
}
在这个例子中,我们定义了一个10个channel的数组(名为chs),并且把庶族中的每个channel分配给10个不同的goroutine。在每个goroutine的add()函数完成后,我们通过
ch <- 1语句向对应的channel写入一个数据。在这个channel被读取前,这个操作是阻塞的。在所有的goroutine都启动完成后,我们通过<-ch 语句从10个channel中一次读取数据,在对应的channel数据写入前,这个操作也是阻塞的。
// fuck.go
package main
import (
"fmt"
)
func Count(ch chan int) {
fmt.Printf("Counting")
ch <- 1
}
func main() {
chs := make([]chan int, 10)
for i := 0; i < 10; i++ {
chs[i] = make(chan int)
go Count(chs[i])
}
for _, ch := range chs {
fmt.Printf("\n")
fmt.Print(<-ch)
}
}
在这个例子中,我们定义了一个10个channel的数组(名为chs),并且把庶族中的每个channel分配给10个不同的goroutine。在每个goroutine的add()函数完成后,我们通过
ch <- 1语句向对应的channel写入一个数据。在这个channel被读取前,这个操作是阻塞的。在所有的goroutine都启动完成后,我们通过<-ch 语句从10个channel中一次读取数据,在对应的channel数据写入前,这个操作也是阻塞的。
相关文章推荐
- POJ 2262 Goldbach's Conjecture(素数)
- Google推荐的图片加载库Glide介绍
- Go语言学习笔记2
- 【Algothrim】Dijkstra 实例一
- hrbust 1587 Gragon Island【模拟+递归Dfs+栈】
- Go语言_Go语言的channel
- mongo 更新数组 键值对
- beego使用migrate错误
- Go语言学习:Channel
- 研究Extension和Category的一个例子
- POJ 2195 Going Home (最小费用最大流)
- 论文笔记 | Going deeper with convolutions
- Django项目结构布局
- LightOJ 1030 Discovering Gold
- mongo的数据备份
- Poj 2723 Go Deeper【2-SAT-----Tarjan强连通+二分】
- 特殊矩阵——三对角矩阵(Tridiagonal Matrix)
- hdu_3966_Aragorn's Story(树链剖分裸题)
- hdu_3966_Aragorn's Story(树链剖分裸题)
- 【读书笔记】Zygote 和 System 进程的启动过程