Skip to content

Instantly share code, notes, and snippets.

@tao-yi
Created August 11, 2021 03:45
Show Gist options
  • Save tao-yi/0d0ac7df449e7583362446e22a93e503 to your computer and use it in GitHub Desktop.
Save tao-yi/0d0ac7df449e7583362446e22a93e503 to your computer and use it in GitHub Desktop.
golang concurrency
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func main() {
tasks := []string{"task1", "task2", "task3", "task4", "task5", "task6"}
ch := make(chan string, 3)
var wg sync.WaitGroup
go worker(&wg, ch)
go worker(&wg, ch)
go worker(&wg, ch)
go worker(&wg, ch)
go worker(&wg, ch)
go worker(&wg, ch)
for _, task := range tasks {
wg.Add(1)
ch <- task
}
close(ch)
wg.Wait()
}
func worker(wg *sync.WaitGroup, ch chan string) {
for t := range ch {
process(t)
wg.Done()
}
}
func process(s string) {
fmt.Printf("start processing %s\n", s)
time.Sleep(time.Duration(rand.Intn(3)) * time.Second)
fmt.Printf("done processing %s\n", s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment