使用struct{}作为零开销信号载体,主协程通过接收channel通知等待子任务完成;2. 多个goroutine通过fan-in模式向同一channel发送完成信号,实现统一事件通知。

在Go语言中,channel不仅是数据传递的工具,也常用于信号传递与事件通知。这类场景下,我们并不关心传递的数据内容,而是在于“某个事件发生了”这一事实。下面通过几个典型示例说明如何使用channel实现事件通知机制。
由于struct{}不占用内存空间,常被用作纯粹的信号载体。
示例:主协程等待子协程完成任务
package main
<p>import (
"fmt"
"time"
)</p><p>func worker(done chan struct{}) {
fmt.Println("工作开始...")
time.Sleep(2 * time.Second) // 模拟耗时操作
fmt.Println("工作完成")
close(done) // 通过关闭channel发送完成信号
}</p><p>func main() {
done := make(chan struct{})</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">go worker(done)
<-done // 阻塞等待,直到收到完成信号
fmt.Println("接收到完成通知,主程序退出")}
立即学习“go语言免费学习笔记(深入)”;
多个goroutine完成各自任务后,向同一个channel发送信号,主协程统一接收。
func doTask(id int, ch chan<- struct{}) {
fmt.Printf("任务 %d 开始\n", id)
time.Sleep(time.Duration(id) * time.Second)
fmt.Printf("任务 %d 完成\n", id)
ch <- struct{}{}
}
<p>func main() {
const numTasks = 3
ch := make(chan struct{}, numTasks) // 缓冲channel避免阻塞发送</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">for i := 1; i <= numTasks; i++ {
go doTask(i, ch)
}
// 等待所有任务完成
for i := 0; i < numTasks; i++ {
<-ch
}
fmt.Println("所有任务已完成")}
立即学习“go语言免费学习笔记(深入)”;
结合select和time.After实现带超时的事件等待。
func fetchData(ch chan string) {
time.Sleep(3 * time.Second)
ch <- "数据获取成功"
}
<p>func main() {
result := make(chan string, 1)</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">go fetchData(result)
select {
case data := <-result:
fmt.Println(data)
case <-time.After(2 * time.Second):
fmt.Println("请求超时")
}}
立即学习“go语言免费学习笔记(深入)”;
对于更复杂的场景,推荐使用context配合channel实现取消信号广播。
func worker(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("收到取消信号,退出工作")
return
default:
fmt.Print(".")
time.Sleep(500 * time.Millisecond)
}
}
}
<p>func main() {
ctx, cancel := context.WithCancel(context.Background())
go worker(ctx)</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">time.Sleep(3 * time.Second)
cancel() // 发送取消通知
time.Sleep(1 * time.Second) // 等待worker退出}
立即学习“go语言免费学习笔记(深入)”;
基本上就这些常见模式。核心在于理解channel不仅可以传数据,还能表达“状态变化”或“时机同步”。选择close(channel)、发送空结构体还是结合context,取决于具体场景的复杂度和可维护性需求。不复杂但容易忽略的是缓冲大小和资源释放问题。
以上就是Golangchannel信号传递与事件通知示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号