Skip to content

Instantly share code, notes, and snippets.

@obutora
Last active May 20, 2024 13:10
Show Gist options
  • Save obutora/4e44ecaa4d5ba04394b05c685d2f5670 to your computer and use it in GitHub Desktop.
Save obutora/4e44ecaa4d5ba04394b05c685d2f5670 to your computer and use it in GitHub Desktop.
channelを閉じることでgoroutineをトリガする
package main
import (
"fmt"
"sync"
)
func main() {
begin := make(chan bool, 10)
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(num int) {
// channelに値が入るまで待機
<-begin
fmt.Printf(fmt.Sprintf("trigger: %d\n",num))
wg.Done()
}(i)
}
fmt.Println("close channel")
// ここでgoroutineを同時にトリガーする
close(begin)
// closeよりも先に Wait() が呼ばれると、channnelがcloseされないためデッドロックとなる
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment