golang之channel

Buffered Channels

package main

import "fmt"

func main() {
	ch := make(chan int, 2)
	ch <- 1
	ch <- 2
	fmt.Println(<-ch)
	fmt.Println(<-ch)
}

如果操作一个空的channel会怎么样呢?

package main

import "fmt"

func main() {
	ch := make(chan int, 2)
	ch <- 1
	ch <- 2
	fmt.Println(<-ch)
	fmt.Println(<-ch)

	v, ok := <-ch
	fmt.Println(v,ok)
}

1
2
fatal error: all goroutines are asleep - deadlock!

 

如果make函数不指定buffer length,会怎么样呢?

func main() {
	ch := make(chan int)
	ch <- 1
	fmt.Println(<-ch)
}

fatal error: all goroutines are asleep - deadlock!

 

上述例子中sender,receiver都是同一个线程。

如果sender,receiver是不同线程会怎么样呢?

package main

import "fmt"
import "time"

func WriteChannel(c chan int, v int) {
	fmt.Printf("write %d to channel\n", v)
	c <- v
}
func main() {
	c := make(chan int)
	
	go WriteChannel(c,1)
	fmt.Println(<-c)
	
	time.Sleep(100 * time.Millisecond)
	fmt.Printf("Done\n")
}

运行又正常了。

 

posted @ 2017-12-07 11:14  Sawyer Ford  阅读(183)  评论(0编辑  收藏  举报