sync实例:
package main
import (
"fmt"
"sync"
)
var waitgroup sync.WaitGroup
func Afunction(shownum int) {
fmt.Println(shownum)
waitgroup.Done() //任务完成,将任务队列中的任务数量-1,其实.Done就是.Add(-1)
}
func main() {
for i := 0; i < 10; i++ {
waitgroup.Add(1) //每创建一个goroutine,就把任务队列中任务的数量+1
go Afunction(i)
}
waitgroup.Wait() //.Wait()这里会发生阻塞,直到队列中所有的任务结束就会解除阻塞
}
无缓存的channel实例:
package main
import "fmt"
func Afuntion(ch chan int) {
fmt.Println("finish")
<-ch
}
func main() {
ch := make(chan int) //无缓冲的channel
go Afuntion(ch)
ch <- 1
// 输出结果:
// finish
}
有缓存的channel实例:
package main
import "fmt"
func main() {
var ch = make(chan int,20)
for i := 0; i < 10; i++ {
ch <- i
}
close(ch)
//ch <- 11 //panic: runtime error: send on closed channel
for i := range ch {
fmt.Println(i) //输出0 1 2 3 4 5 6 7 8 9
}
}
超时处理channel实例:
package main import ( "fmt" "time")func main() { c := make(chan int) o := make(chan bool) go func() { for { select { case i := <-c: fmt.Println(i) case <-time.After(time.Duration(3) * time.Second): //设置超时时间为3s,如果channel 3s钟没有响应,一直阻塞,则报告超时,进行超时处理. fmt.Println("timeout") o <- true break } } }() <-o}