duanmo5724 2019-03-29 10:29
浏览 5
已采纳

常规比赛条件解决方案

I'm trying to understand how can I fix this race condition for below code.

sayHello := func() {
    fmt.Println("Hello from goroutine")
}

go sayHello()
time.Sleep(1)

fmt.Println("Hello, playground")

Expectation: I just want to know whats the best solution, should I use WaitGroup or is there any better solution ?

So I came up with below solution :

var wg sync.WaitGroup
//defer wg.Wait()
sayHello := func() {
    defer wg.Done()
    fmt.Println("Hello from goroutine")
}
wg.Add(1)

go sayHello()
wg.Wait()

fmt.Println("Hello, playground")

But its blocking the main goroutine until code is executed !

As well, if I use defer wg.Wait() the output is different ! https://play.golang.org/p/_xkLb7HvNF8

Race condition I meant where go sayHello() never even gets executed, cause the main func will finish executing before the goroutine even started. Hence it creates a race condition if I try to put a time.Sleep

  • 写回答

1条回答 默认 最新

  • douhong1703 2019-03-29 10:41
    关注

    There is no a race condition in your code.

    First question

    But its blocking the main goroutine until code is executed !

    You are using right after the sayHello call:

    wg.Wait()
    

    This blocks your code and waits until the goroutine will be executed. So, go sayHello() will print "Hello from goroutine" always before "Hello, playground".

    See documentation here:

    Wait blocks until the WaitGroup counter is zero.

    Second question

    As well, if I use defer wg.Wait() the output is different !

    Yes, in this case wg.Wait() will be executed before exit the main function. This means sayHello() will print "Hello from goroutine" before or after "Hello, playground" - this depends on Go scheduler

    See more about defer here

    A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions.

    Update:

    Using WaitGroup is recommended in comparison to another solution using channels. You should use wg.Wait() at the right place to achieve the expected output (still not provided).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。