跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

go 通道出现问题,在封闭通道上发送

php小编柚子在使用Go语言开发过程中,可能会遇到一些问题,其中之一就是在封闭的通道上发送数据时出现了问题。这个问题可能会导致通道的阻塞和程序的停滞,影响整个应用的运行。在解决这个问题之前,我们首先需要了解什么是封闭通道,以及为什么在封闭通道上发送数据会出现问题。接下来,我们将深入探讨这个问题,并提供解决方案来修复和优化我们的Go应用程序。 问题内容 我收到一个致命错误:“在关闭的通道上发送”,有时我运行此代码,我尝试了多种解决方案,但没有一个有效,这是代码的表示,易于理解且易于使用测试: CB14CE50B218D8EAB916B15CD95527D5 我想要的是启动请求函数n次并获取第一个完成的请求,然后关闭通道并且不要向通道发送更多请求,如果没有一个请求成功完成,则等待所有goroutines完成. 我想发生这种情况是因为两个或多个 goroutine 同时检查通道是否关闭,并且两个都尝试在通道中写入,这会导致致命错误。 错误: go语言参考手册 中文CHM版 Go 是一个开源的编程语言,它能让构造简单、可靠且高效的软件变得容易。本文给大家带来Go参考手册,需要的可以来下载! Go是从2007年末由Robert Griesemer, Rob Pike, Ken Thompson主持开发,后来还加入了Ian Lance Taylor, Russ Cox等人,并最终于2009年11月开源,在2012年早些时候发布了Go 1稳定版本。现在Go的开发已经是完全开放的,并且拥有一个活跃的社区。 Go 语言特色 简洁、快速、安全 并行、有趣、开源 内存管理、v数组安全、编译 下载
goroutine 19 [running]: main.request(0xc00000a028, 0xc00000a030, 0x0?) C:/test/main.go:49 +0x135 created by main.main C:/test/main.go:17 +0xd3 panic: send on closed channel
谁能解释一下为什么会发生这种情况? 提前致谢 解决方法 问题是接收 goroutine (
main
) 过早关闭
outputCh
。其他一些 goroutine 仍然可以尝试在其上发送。 这是另一种方法:
package main import ( "fmt" "math/rand" "sync" "time" ) func main() { var wg sync.WaitGroup output := make(chan string) stop := make(chan bool) done := make(chan bool) for i := 0; i < 20; i++ { wg.Add(1) go request(output, stop, &wg) } go func() { wg.Wait() done <- true }() firstOutput := <-output fmt.Println("output:", firstOutput) fmt.Println("closing the stop channel") close(stop) <-done fmt.Println("end of main") } func request(output chan string, stop chan bool, wg *sync.WaitGroup) { defer wg.Done() fmt.Println("request started") time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) select { case output <- "test": fmt.Println("output sent") case <-stop: fmt.Println("stop channel is closed") } }

相关文章