在Go中,可以使用通道来实现不使用互斥锁的goroutine。
下面是一个示例代码,展示了如何使用通道来同步goroutine:
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
done := make(chan bool)
// 启动goroutine
go worker(ch, done)
// 发送数据到通道
ch <- 42
// 等待goroutine完成
<-done
fmt.Println("All done!")
}
func worker(ch chan int, done chan bool) {
// 从通道接收数据
data := <-ch
fmt.Println("Received:", data)
// 模拟耗时操作
time.Sleep(2 * time.Second)
// 发送完成信号到通道
done <- true
}
在上面的示例中,我们创建了两个通道 ch
和 done
。ch
用于发送数据到goroutine,done
用于接收goroutine完成的信号。
在 main
函数中,我们启动了一个goroutine,并向 ch
通道发送了一个值。然后,我们通过 <-done
语句等待goroutine完成的信号。
在 worker
函数中,我们使用 <-ch
语句从 ch
通道接收数据,并进行一些处理。然后,我们通过 done <- true
语句向 done
通道发送完成信号。
通过使用通道来同步goroutine,我们避免了使用互斥锁来保护共享数据。