4
4

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.

ゴルーチン(1)

4
Last updated at Posted at 2014-11-21

goroutine に手を出してみる。

func main() {
  go func() {
    println("hogehoge")
  }
}

これはシンタックスエラーになる。
javascript等のように無名関数を実行せずに渡す書き方ではない。deferと同じ。
なので、

func main() {
  go func() {
     println("hogehoge")
  }()
}

としないといけない。無名関数の最後に () が必要。
シンタックスエラーはなくなるが、このままでは標準出力への出力がされずにプロセスが終了してしまう。

channelを使って待たせてみればOK

fumc main() {
  ch := make(chan string)
  defer close(ch)
  go func() {
    ch <- "hogehoge"
  }()
  println(<-ch)
}

あれ、これでいいのか?
そもそもgoroutine で標準出力に出したかったのに、処理自体の意味合いが変わってしまっている感じがする。

sync.WaitGroup を使ってみよう。

import "sync"

func main() {
  wg := &sync.WaitGroup{}
  wg.Add(1)
  go func() {
    println("hogehoge")
    wg.Done()
  }()
  wg.Wait()
}

goroutine 側で標準出力に出したかった目的を達成できた。
保持したい側で wg.Addして、処理する側で wg.Doneする。
sync.WaitGroup 以外と簡単かも。

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?