Rmartinez
Rmartinez

Reputation: 21

Running multiple go routines at the same time

I want to run multiple Go routines. I want them to all start up the same time. I added another sync waitGroup and added a wait inside the start of the go routine. This however did not work to have all the go routine start at the same time. What should I do in order to have a number of go routines to start exactly at the same time?

package main

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

func main() {
     var wg sync.WaitGroup
      routines := flag.Int("runs", 100, "routines running")
      flag.Parse()

      wg.Add(*routines)

      for i := 0; i < *routines; i++ {
              go func() {
                      defer wg.Done()
                      t := time.Now()
                      fmt.Printf("%s\n", t)
              }()
      }
      fmt.Println("Waiting To Finish")
      wg.Wait()

Upvotes: 2

Views: 4676

Answers (1)

JimB
JimB

Reputation: 109339

You can have all goroutines block on a channel, and close that channel once they are all dispatched:

start := make(chan struct{})

for i := 0; i < *routines; i++ {
    go func() {
        <-start
        defer wg.Done()
        t := time.Now()
        fmt.Printf("%s\n", t)
    }()
}
fmt.Println("starting")
close(start)

This will get you as close to "exactly the same time" as possible. You can't really guarantee that they always run at precisely the same time, and if there are more goroutines than GOMAXPROCS or CPU cores, they can't possibly run at exactly the same time.

Upvotes: 16

Related Questions