more complex example that demonstrates the use of the sync package
This commit is contained in:
parent
6905e99be2
commit
3db7a906de
1 changed files with 50 additions and 0 deletions
50
sync-multi-threaded.go
Normal file
50
sync-multi-threaded.go
Normal file
|
@ -0,0 +1,50 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Task struct representing a task to be processed
|
||||
type Task struct {
|
||||
id int
|
||||
}
|
||||
|
||||
// Worker function that processes tasks from the task channel
|
||||
func worker(id int, tasks <-chan Task, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
for task := range tasks {
|
||||
fmt.Printf("Worker %d processing task %d\n", id, task.id)
|
||||
time.Sleep(time.Millisecond * 500) // Simulate work
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
const numWorkers = 3
|
||||
const numTasks = 10
|
||||
|
||||
// Create a channel to send tasks to workers
|
||||
tasks := make(chan Task, numTasks)
|
||||
|
||||
// Create a WaitGroup to wait for all workers to finish
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// Start worker goroutines
|
||||
for i := 1; i <= numWorkers; i++ {
|
||||
wg.Add(1)
|
||||
go worker(i, tasks, &wg)
|
||||
}
|
||||
|
||||
// Send tasks to the task channel
|
||||
for i := 1; i <= numTasks; i++ {
|
||||
tasks <- Task{id: i}
|
||||
}
|
||||
|
||||
// Close the task channel to signal no more tasks
|
||||
close(tasks)
|
||||
|
||||
// Wait for all workers to finish
|
||||
wg.Wait()
|
||||
fmt.Println("All tasks processed")
|
||||
}
|
Loading…
Reference in a new issue