Jeremy Quinton
Jeremy Quinton

Reputation: 686

Golang go routine concurrency behaviour not working as expected

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")
}

Upvotes: 0

Views: 470

Answers (1)

Jeremy Quinton
Jeremy Quinton

Reputation: 686

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")
}

Upvotes: 4

Related Questions