Last active
May 20, 2024 13:10
-
-
Save obutora/4e44ecaa4d5ba04394b05c685d2f5670 to your computer and use it in GitHub Desktop.
channelを閉じることでgoroutineをトリガする
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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