duanqun9618 2016-02-05 22:16
浏览 85

同时运行多个go例程

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
", t)
              }()
      }
      fmt.Println("Waiting To Finish")
      wg.Wait()
  • 写回答

1条回答 默认 最新

  • doutuoji8418 2016-02-05 22:19
    关注

    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
    ", 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.

    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序