Skip to content

Instantly share code, notes, and snippets.

@burdiuz
Created January 21, 2020 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burdiuz/9f4cbb2b12f16316bfc32fd8060ff915 to your computer and use it in GitHub Desktop.
Save burdiuz/9f4cbb2b12f16316bfc32fd8060ff915 to your computer and use it in GitHub Desktop.
Learning concurrency in go
package main
import (
"fmt"
"time"
)
func seconds(done <-chan int) <-chan time.Time {
out := make(chan time.Time)
go func(out chan time.Time, done <-chan int) {
for {
select {
case <-done:
close(out)
return
case currentTime := <-time.After(time.Second):
out <- currentTime
}
}
}(out, done)
return out
}
func formatTime(in <-chan time.Time) <-chan string {
stringCh := make(chan string)
go func() {
for {
timeValue, ok := <-in
if !ok {
close(stringCh)
return
}
stringCh <- timeValue.Format("15:04:05")
}
}()
return stringCh
}
func printTime(timeCh <-chan string) {
for {
time, ok := <-timeCh
if !ok {
return
}
fmt.Println(time)
}
}
func main() {
end := make(chan int)
timer := formatTime(seconds(end))
go printTime(timer)
time.Sleep(60 * time.Second)
end <- 1
fmt.Println("Time has gone.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment