Last active
November 23, 2018 08:39
-
-
Save woodsmur/d9f6c5ed7cd7f86469d8d1e80b3986d6 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" | |
"time" | |
) | |
type PayloadInt64 struct { | |
number int64 | |
} | |
type Task struct { | |
id int64 | |
payload PayloadInt64 | |
} | |
type TaskResult struct { | |
id int64 | |
result int64 | |
} | |
func sqrWorkderWithTaskID(wg *sync.WaitGroup, tasks <-chan Task, results chan<- TaskResult) { | |
for task := range tasks { | |
time.Sleep(100 * time.Millisecond) | |
fmt.Printf("[task %v] [payload %v]is running\n", task.id, task.payload.number) | |
results <- TaskResult{ | |
id: task.id, | |
result: task.payload.number * task.payload.number, | |
} | |
} | |
wg.Done() | |
} | |
func main() { | |
var wg sync.WaitGroup | |
tasks := make(chan Task, 10) | |
results := make(chan TaskResult, 10) | |
// launching 3 worker goroutines | |
for i := 0; i < 3; i++ { | |
wg.Add(1) | |
go sqrWorkderWithTaskID(&wg, tasks, results) | |
} | |
taskNum := 10 | |
for i := 0; i < taskNum; i++ { | |
tasks <- Task{ | |
id: int64(i), | |
payload: PayloadInt64{ | |
number: int64(i) * 2, | |
}, | |
} | |
} | |
close(tasks) | |
wg.Wait() | |
for i := 0; i < taskNum; i++ { | |
result := <-results | |
fmt.Printf("[result] %v : [task %v] [payload %v]\n", i, result.id, result.result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment