dongqixuan3112 2016-09-08 05:24
浏览 26
已采纳

Goroutines并发的Go例子

I'm new to the Go Language, and learning here: https://tour.golang.org/concurrency/1

When I run https://play.golang.org/p/9JvbtSuv5o the result is:

world
hello
hello

So Added sync.WaitGroup: https://play.golang.org/p/vjdhnDssGk

package main

import (
    "fmt"
    "sync"
    "time"
)

var w sync.WaitGroup

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

func main() {
    w.Add(1)
    go say("world")
    say("hello")
    w.Wait()
}

But the result is same:

world
hello
hello

What is wrong with my code?

Please help,
Thank you for your help.

  • 写回答

3条回答 默认 最新

  • dongyi3776 2016-09-08 05:33
    关注

    w.Done() decrements the WaitGroup counter.
    So your code even sometimes panic: sync: negative WaitGroup counter.

    You have two Goroutines:
    1 - go say("world")
    2 - say("hello") inside main Goroutine
    so use w.Add(2), see this working sample (The Go Playground):

    package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    var w sync.WaitGroup
    
    func say(s string) {
        for i := 0; i < 2; i++ {
            time.Sleep(100 * time.Millisecond)
            fmt.Println(s)
        }
        w.Done()
    }
    
    func main() {
        w.Add(2)
        go say("world")
        say("hello")
        w.Wait()
    }
    

    output:

    world
    hello
    hello
    world
    

    I hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理