Last active
April 5, 2020 09:44
-
-
Save foolishway/af15ad8d4de2578b81e95a70a13596d9 to your computer and use it in GitHub Desktop.
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" | |
"sync" | |
"sync/atomic" | |
"time" | |
) | |
type work struct { | |
x int32 | |
y int32 | |
z int32 | |
} | |
func worker(wg *sync.WaitGroup, input <-chan work, out chan<- work, counter *int32) { | |
defer wg.Done() | |
for w := range input { | |
atomic.AddInt32(counter, 1) | |
w.z = w.x * w.y | |
time.Sleep(time.Duration(w.z) * time.Millisecond) | |
out <- w | |
} | |
} | |
func run(wg *sync.WaitGroup, workerNum int, input <-chan work, out chan<- work, counter *int32) { | |
for i := 0; i < workerNum; i++ { | |
wg.Add(1) | |
go worker(wg, input, out, counter) | |
} | |
} | |
func createWork(workNum int32, input chan<- work) { | |
var ( | |
w work | |
i int32 | |
) | |
for i = 0; i < workNum; i++ { | |
w = work{x: i, y: i} | |
input <- w | |
} | |
close(input) | |
} | |
func consumer(output <-chan work) { | |
for w := range output { | |
fmt.Println(w.z) | |
} | |
fmt.Println("All tasks consumed.") | |
} | |
func main() { | |
input, output := make(chan work, 10), make(chan work, 10) | |
defer close(output) | |
wg := &sync.WaitGroup{} | |
var counter int32 = 0 | |
run(wg, 10, input, output, &counter) | |
go createWork(50, input) | |
go consumer(output) | |
wg.Wait() | |
fmt.Printf("All task was completed, total %d tasks.\n", counter) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment