Created
January 21, 2020 10:29
-
-
Save burdiuz/9f4cbb2b12f16316bfc32fd8060ff915 to your computer and use it in GitHub Desktop.
Learning concurrency in go
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 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