Skip to content

Instantly share code, notes, and snippets.

@satoryu
Last active May 15, 2019 05:47
Show Gist options
  • Save satoryu/8c78061ac5b4031db934bb78a3789571 to your computer and use it in GitHub Desktop.
Save satoryu/8c78061ac5b4031db934bb78a3789571 to your computer and use it in GitHub Desktop.
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
}
@nisshiee
Copy link

[IMO] 読み取りチャネルとして使うことを明示してやると良さそうです

func Screaming(names <-chan string, control <-chan bool) {

[IMO] チャネルはcloseしないと生存し続けるので defer close() するのを癖にするぐらいで良いかと思います(今回はプログラムが終了するので問題ないですが)

ch := make(chan string)
defer close(ch)
c := make(chan bool)
defer close(c)

[応用] 「数秒おきに処理」は Ticker を使った実装も良さげです

[応用] キャンセル処理は context を使った実装が、ちょっと難しいですけど慣れると最高です

@satoryu
Copy link
Author

satoryu commented May 15, 2019

寿司ゆき:thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment