Created
August 11, 2021 03:45
-
-
Save tao-yi/0d0ac7df449e7583362446e22a93e503 to your computer and use it in GitHub Desktop.
golang concurrency
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" | |
"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