如果你有一个单独的goroutine在做某事,并且想在继续进行之前等待它完成,那么你可以使用下面的例子。
例子
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan bool)
go paint(ch)
// Acquire lock by waiting for channel to send something.
<- ch
fmt.Println("done")
}
func paint(ch chan <- bool) {
fmt.Println("started painting")
time.Sleep(2 * time.Second)
fmt.Println("finished painting")
// Instruct to release lock by sending a message.
ch <- true
}
started painting
finished painting
done