Channel based concurrency in Go
package main
import (
"fmt"
"time"
)
func worker(ch chan int) {
time.Sleep(time.Second)
fmt.Println(time.Now())
<-ch
}
func main() {
// task number
count := 10
ch := make(chan int, 3)
defer close(ch)
for i := 0; i < count; i++ {
ch <- 0
go worker(ch)
}
// wait task finish
for {
if len(ch) == 0 {
break
}
time.Sleep(time.Second)
}
fmt.Printf("# DONE\n")
}
Disclaimer
- License under
CC BY-NC 4.0
- Copyright issue feedback
me#imzye.me
, replace # with @ - Not all the commands and scripts are tested in production environment, use at your own risk
- No privacy information is collected here
Try iOS App