0
0

More than 3 years have passed since last update.

【Golang】ゴルーチン③バッファ、チャネル

Posted at

【Golang】ゴルーチン③バッファ、チャネル

Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main
//Buffered Channels
//同じチャネルに複数ゴルーチンから送信

import "fmt"

func main() {
    //1
    //channelを作成 2はバッファ 2つまで受け取る。長さ
    //3つあるとエラーになる
    ch := make(chan int, 2)
    ch <- 1000
    fmt.Println(len(ch))
    //>>1

    ch <- 2000
    fmt.Println(len(ch))
    //>>2

    //ch <- 300はバッファサイズ以上になる為、エラー(デッドロック)

    //2
    //一つ取り出す。channelの中は1つ減るため、追加できる
    /*
    x := <- ch
    fmt.Println(x)
    ch <- 3000
    */


    //3
    //forで取り出す
    //2つ以上取りに行くため、エラーになる。
    //チャネルに3つ目がないのに撮りに行こうとする為。
    //close(ch)にすることで、それ以上読み込まなくなり、エラーがなくなる
    //rangeで回す場合は必要
    //close()で全て入ったら閉じる
    close(ch)
    for c := range ch {
        fmt.Println(c)
    }
    /*
    1000
    2000
    */
}

/*
close
バッファ内が空になったりクローズされたりしても、チャネルが内包する型の初期値を受信する
ch := make(chan iont, 3)
ch <- 1
ch <- 2
ch <- 3
close(ch)
i, ok<- ch
//>>1, true
i, ok<- ch
//>>2, true
i, ok<- ch
//>>3, true
i, ok<- ch
//>>0, false
i, ok<- ch
//>>0, false
*/
0
0
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
0
0