英文:
How to pass a channel to a function as a parameter?
问题
我尝试了两种将通道作为参数传递给函数的方法,但它们都失败了(死锁):
尝试1:
func done(signal *chan bool) {
*signal <- true
}
func main() {
signal := make(chan bool)
done(&signal)
<-signal
fmt.Println("completed")
}
尝试2:
func done(signal chan bool) {
signal <- true
}
func main() {
signal := make(chan bool)
done(signal)
<-signal
fmt.Println("completed")
}
我已经没有更多的想法了。传递通道给函数的正确方法是什么?
英文:
I made two attempts to pass a channel to a function as a parameter, but they both fail (deadlock):
Attempt 1:
func done(signal *chan bool) {
*signal <- true
}
func main() {
signal := make(chan bool)
done(&signal)
<-signal
fmt.Println("completed")
}
Attempt 2:
func done(signal chan bool) {
signal <- true
}
func main() {
signal := make(chan bool)
done(signal)
<-signal
fmt.Println("completed")
}
Well I am out of ideas. What should be the proper way to pass the channel to the function?
答案1
得分: 16
默认情况下,通道是无缓冲的,因此当你在通道上发送数据时,发送操作会阻塞,直到有人接收到这个值。在你的代码中,当你执行 signal <- true
时,没有人可以或者将会在同一个通道上接收到这个值。
你可以创建一个 goroutine 来执行发送操作,这样主函数 main() 的执行会继续进行,并且会有一个接收者接收这个值:
go done(signal)
或者你可以创建一个带缓冲的通道,这样如果通道中有足够的空间来存储值,发送操作就不会阻塞:
signal := make(chan bool, 1)
英文:
A channel is unbuffered by default, so when you send on a channel, that send will block
until someone receives the value. This is clearly the case in your code here, at the point where you you're doing signal <- true
, there's noone that can or ever will receive on the same channel.
You can create a goroutine that does the sending, that way execution in main() continues and there will be someone that's receiving the value:
go done(signal)
Or you can create a buffered channel, so sending on a channel doesn't block if there's room for the value in the channel:
signal := make(chan bool, 1)
答案2
得分: 5
done(&signal)
是同步调用的。也许你想要的是异步调用它?
要实现异步调用,可以在函数调用前加上关键字go
:
go done(&signal)
主线程将会阻塞,直到done
函数向通道写入数据。而done
方法将会在向通道写入数据时阻塞,直到主线程读取通道的数据。
英文:
done(&signal)
is called synchronously. Maybe what you wanted to do is to call it asynchronously?
to do so, put the keyword go
in front of the function call
go done(&signal)
The main thread will block until the done function writes to the channel. And the done method will block on writing to the channel until the main thread reads the channel.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论