Skip to content

Instantly share code, notes, and snippets.

@oze4
Created December 18, 2021 03:43
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 oze4/99d42ce1f535b331d026ecd29182c0d5 to your computer and use it in GitHub Desktop.
Save oze4/99d42ce1f535b331d026ecd29182c0d5 to your computer and use it in GitHub Desktop.
golang wait for x time channel (no wait groups)
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