为什么运行某些goroutines需要time.sleep? [英] Why is time.sleep required to run certain goroutines?

查看:108
本文介绍了为什么运行某些goroutines需要time.sleep?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在GO教程中,我们有这张幻灯片:

http://tour.golang.org/#62

 包主

导入(
fmt
time


func say(s string){
for i:= 0;我< 5; i ++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}

func main(){
go say(world)
say(hello)
}

运行这段代码会产生预期的结果(交替写入屏幕5次的world和hello)。然而,如果我们注释掉 time.Sleep (因此,导入的time行)并再次运行该程序,我们将只有 hello五次写入屏幕。



关于 time.Sleep time.Sleep 这样可以节省goroutine的死亡时间吗?

解决方案

/ code>你不会给 say(world) goroutine一个运行的机会。 goroutine调度程序不是抢先式的。在另一个goroutine运行之前,你的goroutines必须放弃控制权。放弃控制的一种方法是运行 time.Sleep



如果您取出 time.Sleep 函数,然后主要goroutine运行5次而不放弃对次要goroutine的控制,然后当主要goroutine从返回 程序退出,因为程序没有任何活动。


In the GO tutorial, we have this slide:

http://tour.golang.org/#62

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    go say("world")
    say("hello")
}

Running this code produces expected results ("world" and "hello" written to the screen interchangeably 5 times).

However, if we comment out time.Sleep (and consequently, the "time" line of the import) and run the program again, we are left with only "hello" written to the screen five times.

What is so important about time.Sleep that saves the goroutine from dying?

解决方案

If you remove the time.Sleep you don't give the say("world") goroutine a chance to run. The goroutine scheduler is not preemptive. Your goroutines have to give up control before another goroutine will run. One way to give up control is to run time.Sleep.

If you take out the time.Sleep from the say function then the primary goroutine runs 5 times without giving up control to the secondary goroutine and then when the primary goroutine returns from say the program exits because there is nothing to keep the program alive.

这篇关于为什么运行某些goroutines需要time.sleep?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆