3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

sync.WaitGroupで非同期処理

Last updated at Posted at 2017-12-07

複数のgoroutineで並列処理するならWaitGroupが便利だって聞いた:blush:

waitgroup.go
package main

import (
	"fmt"
  "sync"
)

func main() {
  wait := &sync.WaitGroup{} // WaitGroup作成
  for i := 0; i < 10; i++ {
    index := i
    wait.Add(1) // waitインクリメント
      go func() {
          defer wait.Done() // goroutineが終わったらデクリメント

          if err := DoSomething(); err != nil {
            fmt.Println("error!", index)
            return // deferでwait.Done()することで、return処理が書きやすい
          }

          fmt.Println("success!", index)
      }()
  }
  wait.Wait() // 全てのwaitの終了を待つ
}

func DoSomething() error {
  // do something
  return nil
}
$ go run waitgroup.go
success! 9
success! 2
success! 3
success! 1
success! 6
success! 5
success! 7
success! 8
success! 0
success! 4
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?