funcmain(){ var a [10]int for i := 0; i < 10; i++ { gofunc(i int) { for { a[i]++ //fmt.Printf("Hello from goroutine %d\n", i) //io操作会进行切换,会有等待过程,所以可以让其他协程运行 } }(i) } time.Sleep(time.Millisecond) fmt.Println(a) }
funcworker(id int, c chanint) { for { fmt.Printf("worker %d received %d \n", id, <-c) } }
funcbufferChannelClose() { // 第二个参数表示缓冲区,就是可以存放的等待数为4个 c := make(chanint, 4) go worker(0, c) c <- 2 c <- 2 c <- 2 c <- 2 close(c) } // 有一个goroutine发数据,必须有一个goroutine收数据, 不然就不能放进去了, 会报异常deadlock // fatal error: all goroutines are asleep - deadlock!
funcdoWork(id int, c chanint) { // 可以取出所有channel中传送的数据 for n := range c { fmt.Printf("worker %d received %d \n", id, n) }
// 另一种方式 // for { // if n, ok := <-c; !ok { // break // } else { // fmt.Printf("worker %d received %c \n", id, n) // } // } }
funcchannelClose() { c := make(chanint) go doWork(0, c) c <- 2 c <- 2 c <- 2 c <- 2 close(c) time.Sleep(time.Millisecond) }
funcwork(id int, c chanint, done chanbool) { for n := range c { fmt.Printf("worker %d received %d \n", id, n) // channel有发就要有收,但是在goroutine中另外开启一个goroutine就不用接受 gofunc() { done <- true }() } }
funccreateWorker(id int)worker { w := worker{ make(chanint), make(chanbool), } go work(id, w.in, w.done) return w }
funcchannelDemo() { var workers [3]worker for i := 0; i < 3; i++ { workers[i] = createWorker(i) }
for i := 0; i < 3; i++ { workers[i].in <- i }
for i := 0; i < 3; i++ { workers[i].in <- 'a' + i }
//wait for all task for _, worker := range workers { <-worker.done <-worker.done } }