Wednesday, January 14, 2026

goroutine - 1

 package main


import (

"fmt"

"sync"

"time"

)


func worker(id int, jobs <-chan int, results chan<- string, wg *sync.WaitGroup) {

defer wg.Done()

for job := range jobs {

// Simulate task execution

time.Sleep(time.Millisecond * time.Duration(100+job*10))

results <- fmt.Sprintf("Worker %d processed job %d", id, job)

}

}


func main() {

const numJobs = 50

const maxWorkers = 10


jobs := make(chan int, numJobs)

results := make(chan string, numJobs)

var wg sync.WaitGroup


// Start workers

for w := 1; w <= maxWorkers; w++ {

wg.Add(1)

go worker(w, jobs, results, &wg)

}


// Send jobs

for j := 1; j <= numJobs; j++ {

jobs <- j

}

close(jobs)


// Wait for all workers to finish

go func() {

wg.Wait()

close(results)

}()


// Collect results

var completedTasks []string

for result := range results {

completedTasks = append(completedTasks, result)

}


// Print summary

fmt.Printf("Total tasks completed: %d\n", len(completedTasks))

fmt.Println("Execution completed")

}

No comments:

Post a Comment