Skip to content

Instantly share code, notes, and snippets.

@juusechec
Created March 6, 2021 19:10
Show Gist options
  • Save juusechec/44ff7a1f51cc346e806305e85c95e202 to your computer and use it in GitHub Desktop.
Save juusechec/44ff7a1f51cc346e806305e85c95e202 to your computer and use it in GitHub Desktop.
Go workers example
package main
import (
"fmt"
"time"
)
func printWorker(name string, days int) {
weeks := days / 7
restDays := days % 7
if restDays == 0 {
fmt.Printf("%s ha trabajando en la empresa %d semanas\n", name, weeks)
} else {
fmt.Printf("%s ha trabajando en la empresa %d semanas y %d días\n", name, weeks, restDays)
}
}
// @link: https://tour.golang.org/concurrency/4
func worker(id int, jobs <-chan int, results chan<- int, items map[string]int, keysItems []string) {
for j := range jobs {
//fmt.Println("worker", id, "processing job", j)
index := keysItems[j-1]
printWorker(index, items[index])
time.Sleep(time.Second)
results <- j * 2
}
}
func getKeys(mymap map[string]int) []string {
keys := make([]string, len(mymap))
i := 0
for k := range mymap {
keys[i] = k
i++
}
return keys
}
func main() {
numWorkers := 2
items := map[string]int{"Robert": 30, "John": 475, "Elly": 1022, "Bob": 99}
lenItems := len(items)
keysItems := getKeys(items)
job := make(chan int, 10)
result := make(chan int, 10)
for w := 1; w <= numWorkers; w++ {
go worker(w, job, result, items, keysItems)
}
for j := 1; j <= lenItems; j++ {
job <- j
}
close(job)
for a := 1; a <= lenItems; a++ {
<-result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment