How to pass a channel to a function as a parameter?

huangapple go评论97阅读模式
英文:

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 &lt;- true
}

func main() {
    signal := make(chan bool)
    done(&amp;signal)
    &lt;-signal
    fmt.Println(&quot;completed&quot;)
}

Attempt 2:

func done(signal chan bool) {
    signal &lt;- true
}

func main() {
    signal := make(chan bool)
    done(signal)
    &lt;-signal
    fmt.Println(&quot;completed&quot;)
}

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 &lt;- 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(&amp;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(&amp;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.

huangapple
  • 本文由 发表于 2014年2月20日 15:51:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/21901468.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定