英文:
Parallelisation - Why does sleep pause only once?
问题
为什么只等待第一个goroutine,而其他的则直接执行。我认为这是因为通道c chan string
,但我不理解两者之间的行为。
英文:
Why do wait only the first goroutine with
func Sleep(d Duration)
http://golang.org/pkg/time
"Sleep pauses the current goroutine for the duration d."
but the rest is execute directly. I think cause the channel c chan string
but i dont understand the behaviour between both.
答案1
得分: 4
你的所有go例程都是并发运行的,所以它们都同时休眠4秒钟,因此它们同时结束。
你像这样调用它们。go
意味着所有的getHostName
函数同时运行。
for i := 0; i < max; i++ {
go getHostName(haveHost, ipadresse_3, i)
}
这意味着所有的休眠同时发生。
func getHostName(h chan string, ipAdresse string, n int) {
//这里!!!
time.Sleep(4 * time.Second)
ip := ipAdresse + strconv.Itoa(n)
//ip, ok := net.LookupAddr(ip)
if false {
h <- ip + " - "
} else {
h <- "error" + strconv.Itoa(n)
}
}
所以它们都同时完成。
英文:
All your go routines are running concurrently so they all sleep for 4 seconds at the same time, hence they all end at the same time.
You called them like this. The go
means that all the getHostName
functions run at once.
for i := 0; i < max; i++ {
go getHostName(haveHost, ipadresse_3, i)
}
And this means that all the sleeps happen at the same time
func getHostName(h chan string, ipAdresse string, n int) {
//Here!!!
time.Sleep(4 * time.Second)
ip := ipAdresse + strconv.Itoa(n)
//ip, ok := net.LookupAddr(ip)
if false {
h <- ip + " - "
} else {
h <- "error" + strconv.Itoa(n)
}
}
So they all finish at the same time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论