Skip to content

Instantly share code, notes, and snippets.

@edwardIshaq
Last active April 21, 2019 11:53
Show Gist options
  • Save edwardIshaq/dc0c81e77ae0fae0511baa4a6117ee39 to your computer and use it in GitHub Desktop.
Save edwardIshaq/dc0c81e77ae0fae0511baa4a6117ee39 to your computer and use it in GitHub Desktop.
trying to figure out how to use channels properly
package main
import (
"fmt"
"time"
)
func repeat(done <-chan interface{}, value interface{}) <-chan interface{} {
output := make(chan interface{})
go func() {
defer func() {
fmt.Println("Okay Thats enough")
close(output)
}()
for {
select {
case <-done:
return
case output <- value:
}
}
}()
return output
}
func main() {
fmt.Println("start")
startTime := time.Now()
done := make(chan interface{})
repeatChan := repeat(done, "spin")
timerChan := time.After(10 * time.Millisecond)
loop:
for {
select {
case <-timerChan:
fmt.Println("Timed out")
close(done)
break loop
case value := <-repeatChan:
fmt.Println(value)
}
}
fmt.Println("end")
fmt.Printf("took %v\n", time.Since(startTime))
}
func buggyMain() {
fmt.Println("start")
startTime := time.Now()
done := make(chan interface{})
repeatChan := repeat(done, "spin")
loop:
for {
select {
case <-time.After(10 * time.Millisecond):
fmt.Println("Timed out")
close(done)
break loop
case value := <-repeatChan:
fmt.Println(value)
}
}
fmt.Println("end")
fmt.Printf("took %v\n", time.Since(startTime))
}
@edwardIshaq
Copy link
Author

updated the corrected main

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