@LIUHUAN
2017-11-25T13:07:16.000000Z
字数 1784
阅读 1368
Go
func main() {
in := make(chan int)
out := make(chan int)
go Producer(in)
go Consumer(in, out)
for x := range out { //读取管道,直到关闭,如果没有值,那么阻塞
fmt.Println(x)
}
}
func Consumer(in <-chan int, out chan<- int) {
for x := range in { //读取管道,直到关闭管道为止,没有值,那么阻塞
out <- x * x //写入管道
}
close(out) //关闭写入管道
}
func Producer(out chan<- int) {
for i := 1; i < 10; i++ {
out <- i //写入管道
}
close(out) //关闭写管道
}
ch := make(chan Type,Len)//
ch := make(chan int)//创建一个int类型的管道
x := 1
ch <- x //写入内容
x := <- ch //读取内容
for x := range ch {
//do something with x
}
close(ch)
const (
N = 1000000
Buflen = 100
)
func main(){
main_channel()
main_channel_buffer()
}
func main_channel_buffer() {
start := time.Now()
defer func(){
cost := time.Since(start)
fmt.Println("channel_buffer_cost=",cost)
}()
in := make(chan int,Buflen)
out := make(chan int,Buflen)
go Producer(in)
go Consumer(in, out)
for x := range out {
x += 1
}
}
func main_channel() {
start := time.Now()
defer func(){
cost := time.Since(start)
fmt.Println("channel_cost=",cost)
}()
in := make(chan int)
out := make(chan int)
go Producer(in)
go Consumer(in, out)
for x := range out {
x += 1
}
}
func Consumer(in <-chan int, out chan<- int) {
for x := range in {
out <- x * x
}
close(out)
}
func Producer(out chan<- int) {
for i := 1; i < N; i++ {
out <- i
}
close(out)
}