Skip to content

Instantly share code, notes, and snippets.

@abhisekp
Last active November 5, 2024 04:10
Show Gist options
  • Save abhisekp/210e7b2971747d652b7b0a21f262b9c6 to your computer and use it in GitHub Desktop.
Save abhisekp/210e7b2971747d652b7b0a21f262b9c6 to your computer and use it in GitHub Desktop.
Mastering Go Series
package main
import (
"fmt"
"sync"
"time"
)
const MAX_WORKER_COUNT = 3
const MAX_JOB_COUNT = 5
// Worker-Job frequency
var wFreq = [MAX_WORKER_COUNT]int{}
func worker(id int, jobs <-chan int, wg *sync.WaitGroup) {
for j := range jobs {
wFreq[id-1]++
fmt.Printf("%d: Worker %d started job %d\n", time.Now().Local().Nanosecond(), id, j)
time.Sleep(1 * time.Second)
// Simulate random duration for the job to complete
// time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
// Simulate fixed duration for the job to complete
time.Sleep(100 * time.Millisecond)
fmt.Printf("%d: Worker %d finished job %d\n", time.Now().Local().Nanosecond(), id, j)
wg.Done()
}
}
func main() {
jobs := make(chan int, MAX_JOB_COUNT)
var wg sync.WaitGroup
// Create workers to distribute jobs
for w := 0; w < MAX_WORKER_COUNT; w++ {
go worker(w+1, jobs, &wg)
}
startTime := time.Now()
// Create jobs
for j := 1; j <= MAX_JOB_COUNT; j++ {
wg.Add(1)
jobs <- j
}
close(jobs)
wg.Wait()
fmt.Printf("All %d jobs completed in %d millis with %d workers\n", MAX_JOB_COUNT, time.Since(startTime).Milliseconds(), MAX_WORKER_COUNT)
fmt.Println("Worker Distributions")
for i, v := range wFreq {
fmt.Printf("Worker %d: %d jobs\n", i+1, v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment