Golang 通道同步
如果我们想同步 goroutine ,我们可以使用 通道 。 通过同步,我们想让 goroutine 以一种确定的方式工作,例如,在前一个 goroutine 执行完毕之前,不启动下一个 goroutine 。
通道 有助于实现这一点,因为它们可以用来阻断进程,然后也可以用来通知第二个 goroutine 前一个 goroutine 已经完成它的工作。
例子1
让我们考虑一个非常基本的通道同步的例子,我们将看到如何在缓冲通道的帮助下实现同步。
请看下面的代码。
package main
import (
"fmt"
"time"
)
func check(done chan bool) {
fmt.Print("Welcome to...")
time.Sleep(time.Second)
fmt.Println("TutorialsPoint")
done <- true
}
func main() {
done := make(chan bool, 1)
go check(done)
<-done
}
在上面的代码中,我们对代码进行了同步,因为<- done只是阻断了代码,除非并且直到它收到了值,也就是我们在检查函数里面做的,否则它不会让其他东西执行。
如果我们在上述代码中使用 go run main.go 命令,我们将看到以下输出。
输出
Welcome to...TutorialsPoint
例子2
上面的例子可以用来进一步加强同步,因为通过它,我们可以让一个 goroutine 等待另一个 goroutine。
请看下面的代码。
package main
import (
"fmt"
"time"
)
func check(done chan bool) {
fmt.Print("Welcome to...")
time.Sleep(time.Second)
fmt.Println("TutorialsPoint")
done <- true
}
func check2() {
fmt.Println("Learn Go from here!")
}
func main() {
done := make(chan bool, 1)
go check(done)
if <-done {
go check2()
time.Sleep(time.Second)
}
}
输出
如果我们对上述代码使用 go run main.go 命令,我们将看到以下输出。
Welcome to...TutorialsPoint
Learn Go from here!