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 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)