Last active
April 21, 2019 11:53
-
-
Save edwardIshaq/dc0c81e77ae0fae0511baa4a6117ee39 to your computer and use it in GitHub Desktop.
trying to figure out how to use channels properly
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 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)) | |
} |
updated the corrected main
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
outputs something similar to this but the time it took is inconsistent