标签:
- package main
- import (
- "fmt"
- )
- func main() {
- fmt.Println("Begin doing something!")
- ch := make(chan int)
- go func() {
- fmt.Println("Doing something…")
- ch <- 22
- //close(ch)
- }()
- <-ch //此处将被阻塞,直到ch被关闭 或 有值可以取出
- fmt.Println("Done!")
- }
- package main
- import "fmt"
- func worker(start chan bool, index int) {
- <-start // 从start中取出数据后,调用20行的case语句
- fmt.Println("This is Worker:", index)
- }
- func main() {
- start := make(chan bool)
- for i := 1; i <= 10; i++ {
- go worker(start, i)
- }
- //给start赋值10次,让worker方法执行10次
- for i := 1; i <= 10; i++ {
- start <- true //给start赋值一次,便执行worker函数一次
- }
- v := 1
- //select 被一直阻塞直到start中数据被取出
- select { //deadlock we expected
- case <-start:
- fmt.Print(v)
- v++
- }
- }
- for {
- select {
- case x := <- somechan:
- // … 使用x进行一些操作
- case y, ok := <- someOtherchan:
- // … 使用y进行一些操作,
- // 检查ok值判断someOtherchan是否已经关闭
- case outputChan <- z:
- // … z值被成功发送到Channel上时
- default:
- // … 上面case均无法通信时,执行此分支
- }
- }
- package main
- import (
- "fmt"
- "time"
- )
- func worker(die chan bool, index int) {
- fmt.Println("Begin: This is Worker:", index)
- for {
- select {
- //case xx:
- //做事的分支
- case <-die: //到这里就被阻塞,运行main中的close后输出 done
- fmt.Println("Done: This is Worker:", index)
- return
- }
- }
- }
- func main() {
- die := make(chan bool)
- for i := 1; i <= 10; i++ {
- go worker(die, i)
- }
- time.Sleep(time.Second * 5)
- close(die)
- select {} //deadlock we expected
- }
- package main
- import (
- "fmt"
- //"time"
- )
- func worker(die chan bool) {
- fmt.Println("Begin: This is Worker")
- for {
- select {
- //case xx:
- //做事的分支
- case <-die: //这里等待27行的赋值语句,如果没有赋值,一直阻塞
- fmt.Println("Done: This is Worker")
- die <- true
- return
- }
- }
- }
- func main() {
- die := make(chan bool)
- go worker(die)
- die <- true
- istrue := <-die //这里等待16行的赋值,赋值完毕后程序继续执行
- fmt.Println("Worker goroutine has been terminated", istrue)
- }
标签:
原文地址:http://www.cnblogs.com/anbylau2130/p/4243735.html