duanlian1320 2016-04-02 10:26
浏览 12

Golang Go例行并发行为未按预期工作

Below is a simple go example. I have omitted error handling etc intentionally to make the example short. I have a simple for loop calling the writeOutput function 5 times using the go keyword to make the function run concurrently.

What I expect to happen is 5 files are created in /tmp/ with the contents of test.

What happens is that no files are created.

However if I remove the go keyword the code executes as expected. Im overlooking something super obvious. My background is dynamically typed languages like PHP/Ruby so just getting to grips with go and can't understand why 5 files are created when the go keyword exists.

package main

import (
  "os"
  "math/rand"
  "strconv"
)

func main() {

  for i := 0; i < 5; i++ {
   go writeOutput()
  }

}

func writeOutput() {
  filename := strconv.Itoa(rand.Intn(10000))
  file, _ := os.Create("/tmp/" + filename)
  defer file.Close()
  file.WriteString("test")
}
  • 写回答

1条回答 默认 最新

  • dongmi4927 2016-04-02 10:43
    关注

    I managed to solve this with a wait group as suggested in the comments.

    package main
    
    import (
        "math/rand"
        "os"
        "strconv"
        "sync"
    )
    
    func main() {
    
        var wg sync.WaitGroup
    
        for i := 0; i < 5; i++ {
            wg.Add(1)
            go func() {
                defer wg.Done()
                writeOutput()
            }()
        }
        wg.Wait()
    
    }
    
    func writeOutput() {
        filename := strconv.Itoa(rand.Intn(10000))
        file, _ := os.Create("/tmp/" + filename)
        defer file.Close()
        file.WriteString("test")
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line