| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package main
- import (
- "context"
- "fmt"
- "sync"
- "time"
- )
- func main() {
- workerSize := 10
- dataChan := make(chan int, workerSize)
- stopChan := make(chan bool)
- waitChan := make(chan bool)
- timeoutCtx, cancel := context.WithTimeout(context.TODO(), 5 * time.Second)
- defer cancel()
- var wg sync.WaitGroup
- // consumer worker
- for i := 0; i < workerSize; i++ {
- // worker
- go func(n int) {
- L:
- for {
- select {
- case v := <-dataChan:
- //time.Sleep(6*time.Second)
- fmt.Printf("Worker %d do %d \n", n, v)
- wg.Done()
- case <-stopChan:
- break L
- }
- }
- }(i)
- }
- // provider
- dataSize := 100
- wg.Add(dataSize)
- go func() {
- for i := 0; i < dataSize; i++ {
- dataChan <- i
- }
- }()
- // wait
- go func() {
- wg.Wait()
- waitChan <- true
- }()
- select {
- case <-waitChan:
- fmt.Println("Ok")
- case <-timeoutCtx.Done():
- fmt.Println("Timeout")
- }
- close(stopChan)
- fmt.Println("Exit")
- }
|