我在(https://www.geeksforgeeks.org/channel-in-golang/)上读到:
“在信道中,发送和接收操作阻塞,直到另一端默认未就绪。它允许戈鲁廷在没有显式锁或条件变量的情况下相互同步。
为了测试上面的语句,我编写了一个示例程序,如下所述:
程序:
package main
import (
"fmt"
"sync"
"time"
)
func myFunc(ch chan int) {
fmt.Println("Inside goroutine:: myFunc()")
fmt.Println(10 + <-ch) //<-- According to rule, control will be blocked here until 'ch' sends some data so that it will be received in our myFunc() go routine.
}
func main() {
fmt.Println("Start Main method")
// Creating a channel
ch := make(chan int)
go myFunc(ch) //<-- This go routine started in a new thread
time.Sleep(2 * time.Second) //<--- introduced a Sleep of 2 seconds to ensure that myFunc() go routine executes before main thread
ch <- 10
fmt.Println("End Main method")
}
我期待下面的输出:
Start Main method
Inside goroutine:: myFunc()
20
End Main method
但是,实际接收的输出是:
Start Main method
Inside goroutine:: myFunc()
End Main method
为什么通过通道发送的值没有打印出来?我认为,这是因为主线程首先完成了它的执行,因此,所有其他goroutine也终止了。
如果是这样的话,那么,为什么规则说 - 它允许goroutine在没有显式锁或条件变量的情况下相互同步。
因为,为了获得预期的输出,我必须使用告诉主线程等待另一个 goroutine 完成。这不是违反了上述规则,因为我以等待组的形式使用锁?sync.WaitGroup
PS:我正在学习戈朗。所以,如果我完全理解了这个概念,请原谅。
江户川乱折腾
BIG阳
蓝山帝景
长风秋雁
相关分类