LoginSignup
1
1

More than 5 years have passed since last update.

GO並列処理:Goroutine

Last updated at Posted at 2017-11-02

Goroutine

ci := make(chan int) //bufferなし
cj := make(chan int, 0) //bufferなし
cs := make(chan int, 100) //bufferあり

1.bufferなしの場合、先に書き込み、あとで取る
image.png

 chan <- 1 
 <-chan

2.bufferある場合(データを保存する場合)、先に取る、あとで書き込み
image.png

チャンネルで止める
最後の数で判断するではなく、同時で進行してるから、もしかしたら、最後のやつ一番最初に実行しちゃうかもしれない。(10回の場合)チャンネルの容量を10に設定し、10回やりとりするのが正しい

image.png

syncで止める
image.png

select:どっちのcaseが終わったら終わり

image.png

ch := make (chan int, 1)
ch <- 1
select {
case ch <- 2:
default:
    fmt.Println("channel is full !")
}

容量1であるので、ch<-1入ったらもう満員の状況です、なので、case ch<-2 実行しない。

注意するところ:
time関数
closure関数、引数として渡さないと、GOは自動的にアドレス渡しちゃうので、 『{1,2,3}->3』
最後の値しか出力しない。引数として内部closureに渡せば問題です。
image.png

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