下面的代码给出了编译错误,说'unexpected go':
x := go doSomething(arg)
func doSomething(arg int) int{
...
return my_int_value
}
我知道,如果我正常调用函数,即不使用 goroutine 或者我可以使用 channel 等,我可以获取返回值。
我的问题是为什么不能从 goroutine 中获取这样的返回值。
最佳答案
为什么不能从分配给变量的 goroutine 中获取返回值?
运行 goroutine(异步)和从函数中获取返回值本质上是矛盾的 Action 。当您说 go
时,您的意思是“异步执行”或更简单:“继续!不要等待函数执行完成”。但是,当您将函数返回值分配给变量时,您希望该值包含在变量中。所以当你这样做时 x := go doSomething(arg)
你是在说:“继续,不要等待函数!等待-等待-等待!我需要一个可以在x
var 就在下面的下一行!"
channel
从 goroutine 中获取值最自然的方式是 channel 。 channel 是连接并发 goroutine 的管道。您可以将值从一个 goroutine 发送到 channel ,然后将这些值接收到另一个 goroutine 或同步函数中。您可以使用 select
从不破坏并发的 goroutine 轻松获取值:
func main() {
c1 := make(chan string)
c2 := make(chan string)
go func() {
time.Sleep(time.Second * 1)
c1 <- "one"
}()
go func() {
time.Sleep(time.Second * 2)
c2 <- "two"
}()
for i := 0; i < 2; i++ {
// Await both of these values
// simultaneously, printing each one as it arrives.
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
}
}
示例取自 Go By Example
CSP 和消息传递
Go 很大程度上基于 CSP theory .上面的幼稚描述可以根据 CSP 进行精确概述(尽管我认为这超出了问题的范围)。我强烈建议您至少熟悉 CSP 理论,因为它是 RAD。这些简短的引文给出了思考的方向:
As its name suggests, CSP allows the description of systems in terms of component processes that operate independently, and interact with each other solely through message-passing communication.
In computer science, message passing sends a message to a process and relies on the process and the supporting infrastructure to select and invoke the actual code to run. Message passing differs from conventional programming where a process, subroutine, or function is directly invoked by name.
关于go - 从 goroutine 中捕获返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20945069/