Effective Go-5
Concurrency Share by communicating Do not communication by sharing memory; instead,share memory by communicating 通过通讯来共享内存,而不是通过共享内存来通讯 Goroutines go的协程并发在同一地址空间, 更轻量级。 package goroutines_test import ( "fmt" "sync" "testing" "time" ) var wg sync.WaitGroup func Announce(message string, delay time.Duration) { wg.Add(1) go func() { time.Sleep(delay) fmt.Println(message) defer wg.Done() }() } func TestAnnouce(t *testing.T) { Announce("helloworld", time.Second) Announce("helloweida", time.Second) Announce("hellosanding", time.Second) Announce("hellogarlic", time.Second) Announce("helloding", time.Second) wg.Wait() } Channels 可以通过make创建通道,可以通过第二个参数设置是否带有缓冲 ch:=make(chan int, 0) ch:=make(chan int, 100) 可以通过chan完成协程等待, 如果无缓冲通道, 接收者会立即引发等待, 有缓冲通道,数据填满缓冲区时开始等待。 ...