Skip to content

Instantly share code, notes, and snippets.

@gyandeeps
Created July 27, 2025 19:58
Show Gist options
  • Save gyandeeps/9cf006a96de307ef1111821a7fc42f9e to your computer and use it in GitHub Desktop.
Save gyandeeps/9cf006a96de307ef1111821a7fc42f9e to your computer and use it in GitHub Desktop.
Go routines exmaple
package main
import (
"fmt"
"sync"
)
// Producer: generates jobs and sends them to the `jobs` channel
func producer(jobs chan<- int, numJobs int) {
fmt.Println("Producer started", numJobs)
for i := 1; i <= numJobs; i++ {
jobs <- i
fmt.Printf("Produced job %d\n", i)
fmt.Println("Length of Produced job: ", len(jobs))
}
close(jobs) // no more jobs
}
// Worker: processes jobs and sends results to the `results` channel
func worker(id int, jobs <-chan int, results chan<- string, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Worker %d started\n", id)
for job := range jobs {
fmt.Printf("Worker %d started job %d\n", id, job)
// Simulate work with job
results <- fmt.Sprintf("Worker %d processed job %d", id, job)
}
}
// Collector: gathers results from workers
// func collector(results []int, done chan<- struct{}) {
func collector(results <-chan string, done chan<- struct{}) {
fmt.Println("Collector started")
for res := range results {
// fmt.Println("Inside collector: ", res)
fmt.Println("Processed result: ", res)
}
done <- struct{}{}
}
func main() {
numJobs := 10
numWorkers := 1
jobs := make(chan int, numJobs)
results := make(chan string, numJobs)
done := make(chan struct{})
// tempArray := make([]int, 0, numJobs)
var wg sync.WaitGroup
// Start worker goroutines (fan-out)
for w := 1; w <= numWorkers; w++ {
wg.Add(1)
go worker(w, jobs, results, &wg)
}
// Start the collector (fan-in)
go collector(results, done)
// go collector(tempArray, done)
// Start the producer
go producer(jobs, numJobs+3)
// close(jobs)
// Wait until all workers are done, then close the results channel
wg.Wait()
close(results)
// Wait for collector to finish printing all results
<-done
fmt.Println("All jobs processed and collected.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment