GO教程
GO控制语句
GO高级

Go Channel

Go Channel

通道充当管道,我们通过它将类型值从一个 Goroutine 发送到另一个 Goroutine。它保证同步,因为在任何给定时间只有一个 Goroutine 可以访问数据项。数据的所有权在不同的 Goroutine 之间传递。因此,通过设计它避免了共享内存的陷阱并防止竞争条件。

Go Channel Example

package main
import "fmt"
import "time"
func worker(done chan bool) {
   fmt.Print("working...")
   time.Sleep(time.Second)
   fmt.Println("done")
   done <- true
}
func main() {
   done := make(chan bool, 1)
   go worker(done)
   <-done
}
输出:
working...done

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4