Skip to content

Instantly share code, notes, and snippets.

@edwardIshaq
Last active April 21, 2019 11:53
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 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

edwardIshaq commented Apr 21, 2019

outputs something similar to this but the time it took is inconsistent

...
spin
spin
spin
spin
spin
Timed out
end
took 1.515886221s

@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