Created
December 18, 2021 03:43
-
-
Save matthewoestreich/99d42ce1f535b331d026ecd29182c0d5 to your computer and use it in GitHub Desktop.
golang wait for x time channel (no wait groups)
This file contains hidden or 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" | |
"math/rand" | |
"time" | |
) | |
func zzz(tme int) { | |
r := rand.Intn(10) | |
t := time.Duration(r) * time.Microsecond | |
fmt.Sprintln("Sleeping for %d", t) | |
time.Sleep(t) | |
} | |
func simulateJob(index int, item string) string { | |
rand.Seed(time.Now().UnixNano()) | |
sleepTime := rand.Intn(10-3) + 3 | |
zzz(sleepTime) | |
return fmt.Sprintf("%d. %s", index, item) | |
} | |
func work(index int, item string, c chan string) { | |
c <- simulateJob(index, item) | |
} | |
func main() { | |
c := make(chan string) | |
life := 200 | |
defer close(c) | |
letters := []string{"a", "b", "c", "d", "e", "f", "g"} | |
for index, item := range letters { | |
go work(index, item, c) | |
} | |
for { | |
select { | |
case s := <-c: | |
fmt.Printf("out : %+v\n", s) | |
default: | |
time.Sleep(50 * time.Millisecond) | |
if life--; life == 0 { | |
return | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment