Last active
May 15, 2019 05:47
-
-
Save satoryu/8c78061ac5b4031db934bb78a3789571 to your computer and use it in GitHub Desktop.
This file contains 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" | |
"time" | |
) | |
func Screaming(names <-chan string, control <-chan bool) { | |
ticker := time.Tick(500 * time.Millisecond) | |
for { | |
select { | |
case name := <-names: | |
fmt.Printf("%v DEATH!\n", name) | |
case <-ticker: | |
fmt.Println("... DEATH!") | |
case <-control: | |
break | |
} | |
} | |
} | |
func main() { | |
names := []string{"YUIMETAL", "MOAMETAL", "SU-METAL"} | |
ch := make(chan string) | |
defer close(ch) | |
c := make(chan bool) | |
defer close(c) | |
go Screaming(ch, c) | |
for _, name := range names { | |
time.Sleep(4 * time.Second) | |
ch <- name | |
} | |
c <- true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[IMO] 読み取りチャネルとして使うことを明示してやると良さそうです
[IMO] チャネルはcloseしないと生存し続けるので
defer close()
するのを癖にするぐらいで良いかと思います(今回はプログラムが終了するので問題ないですが)[応用] 「数秒おきに処理」は Ticker を使った実装も良さげです
[応用] キャンセル処理は context を使った実装が、ちょっと難しいですけど慣れると最高です