我們可以使用通道在goroutine上同步執(zhí)行程序。這里有一個(gè)使用阻塞接收等待goroutine完成的示例。
這是將在goroutine中運(yùn)行的函數(shù)。 done通道將用來(lái)通知另一個(gè)goroutine這個(gè)函數(shù)的工作已經(jīng)完成,發(fā)送值以通知已經(jīng)完成。
啟動(dòng)一個(gè)goroutine工作程序,給它一個(gè)通知通道。如果從此程序中刪除 <-done 行,程序?qū)⒃诠ぷ鞒绦?worker)啟動(dòng)之前退出。
阻止,直到在通道上收到工作程序的通知。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.com/go/go_environment.html
channel-synchronization.go的完整代碼如下所示 -
package main
import "fmt"
import "time"
// This is the function we'll run in a goroutine. The
// `done` channel will be used to notify another
// goroutine that this function's work is done.
func worker(done chan bool) {
fmt.Print("working...")
time.Sleep(time.Second)
fmt.Println("done")
// Send a value to notify that we're done.
done <- true
}
func main() {
// Start a worker goroutine, giving it the channel to
// notify on.
done := make(chan bool, 1)
go worker(done)
// Block until we receive a notification from the
// worker on the channel.
<-done
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run channel-synchronization.go
working...done