0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

バッファなしチャネルの挙動について

Last updated at Posted at 2025-02-05

🚀 非同期処理(ゴルーチン) = 複数の作業を同時に進める
📩 チャネル = ゴルーチン間でデータをやり取りするための仕組み

だから、Goで 「複数の処理を非同期にしたい」→ ゴルーチン!
「非同期処理同士でデータをやり取りしたい」→ チャネル!

これを覚えておけばバッチリ!😊✨


本題

バッファなしチャネルを作ると、デッドロックする。

package main

import(
	"fmt"
)

func main() {
	ch := make(chan int)
	ch <- 10
	num := <-ch
	fmt.Println(num)
}

実行結果

fatal error: all goroutines are asleep - deadlock!

このコードを実行したときに起こっていること

ch := make(chan int)

これで、チャネルchが作成される。

ch<-10

チャネル10を送信するが、受信先がないのでここでロックしてしまう。
次の行num:=<-chで受信先があるじゃないか!と思うかもしれないが、この行を実行している時点では受信先がないので、この行で受信先をいつまでも待ってしまうことになり、コードがデッドロック状態になっていた、というわけだ。

go routineを使って並列処理にする

package main

import(
	"fmt"
)

func main() {
	ch := make(chan int)
	go func(){
		ch <- 10
	}()
	num := <-ch
	fmt.Println(num)
}

ch<-10の送信部分を並列処理に渡すと、mainでnum:=<-chの受信部分が実行され、numに値を渡せるようになる。


tips: バッファありチャネルなら、バッファ分まではデッドロックが起こらない

func main() {
	ch := make(chan int, 3) //バッファサイズ3
	ch <- 1
	ch <- 2
	ch <- 3
	
	num := <-ch
	fmt.Println(num)
	num = <-ch
	fmt.Println(num)
	num = <-ch
	fmt.Println(num)
}

実行結果

1
2
3

(ちゃんと、FIFOになってる。)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?