2
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.

ゴルーチン(2) チャンネル

Last updated at Posted at 2014-11-22

goroutine 内でループさせてチャンネルで受けとってみる

func main() {
  ch := make(chan int)
  defer close(ch)
  go func() {
    for i := 0; i < 10; i++ {
      ch <- i
    } 
  }()
  for n := range ch {
    println(n)
  }
}

これ、いけそうなんだけど一番最後にエラーが表示される

fatal error: all goroutines are asleep - deadlock!

さっき覚えた sync.WaitGroup ではどうか

import "sync"

func main() {
  ch := make(chan int)
  defer close(ch)
  wg := &sync.WaitGroup{}
  wg.Add(2)
  go func() {
    for i := 0; i < 10; i++ {
      ch <- i
    }
    wg.Done()
  }() 
  go func() {
    for n := range ch {
      println(n)
    }   
    wg.Done()
  }() 
  wg.Wait()
}

これもやはり同じエラーが発生する。
(deferをコメントアウトしたら正常に動作したと記載していたが、間違い)

[追記]
コメントで指摘していただいた点を反映してみると正常動作した。

func main() {
  ch := make(chan int)
  go func() {
    for i := 0; i < 10; i++ {
      ch <- i
    }   
    close(ch) // ここでclose
  }() 
  for n := range ch {
    println(n)
  }
}
2
3
2

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
2
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?