英文:
Need help to understand this weird bahaviour of go routines
问题
我有以下使用Go协程的代码:
package main
import (
"fmt"
"time"
)
func thread_1(i int) {
time.Sleep(time.Second * 1)
fmt.Println("thread_1: i:", i)
}
func thread_2(i int) {
time.Sleep(time.Second * 1)
fmt.Println("thread_2: i:", i)
}
func main() {
for i := 0; i < 100; i++ {
go thread_1(i)
go thread_2(i)
}
var input string
fmt.Scanln(&input)
}
我原本期望每个Go协程都会等待1秒钟,然后打印出它们的i值。
然而,两个Go协程都等待了1秒钟,然后一次性打印出所有的i值。
在同样的背景下,另一个问题是:
我有一个服务器-客户端应用程序,服务器为每个客户端连接生成一个接收器Go协程来接收数据。然后接收器Go协程会生成一个名为processor的工作Go协程来处理数据。可能会有多个接收器Go协程和多个处理器Go协程。
在这种情况下,一些接收器和处理器Go协程可能会无限期地占用资源。
请帮助我理解这种行为。
英文:
I've following code using go routines:
package main
import (
"fmt"
"time"
)
func thread_1(i int) {
time.Sleep(time.Second * 1)
fmt.Println("thread_1: i: ",i)
}
func thread_2(i int) {
time.Sleep(time.Second * 1)
fmt.Println("thread_2: i: ",i)
}
func main() {
for i := 0; i < 100; i++ {
go thread_1(i)
go thread_2(i)
}
var input string
fmt.Scanln(&input)
}
I was expecting each go routine would wait for a second and then print its value of i.
However, both the go routines waited for 1 second each and printed all the values of i at once.
Another question in the same context is:
I've a server-client application where server spawns a receiver go routine to receive data from client one for each client connection. Then the receiver go routine spawns a worker go routine called processor to process the data. There could be multiple receiver go routines and hence multiple processor go routines.
In such a case some receiver and processor go routines may hog indefinitely.
Please help me understand this behaviour.
答案1
得分: 3
你在一个大批处理中同时运行100个运行thread_1的goroutine和100个运行thread_2的goroutine。这200个goroutine中的每一个都会休眠一秒钟,然后打印输出并结束。所以,是的,这种行为是可以预期的:200个goroutine并行地休眠1秒钟,然后200个goroutine并行地打印输出。
(我不理解你的第二个问题)
英文:
You span 100 goroutines running thread_1 and 100 goroutines running thread_2 in one big batch. Each of these 200 goroutines sleeps for one second and then prints and ends. So yes, the behavior is to be expected: 200 goroutines sleeping each 1 second in parallel and then 200 goroutines printing in parallel.
(And I do not understand your second question)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论