Skip to content

Instantly share code, notes, and snippets.

@gigenthomas
Created March 16, 2025 03:50
Show Gist options
  • Select an option

  • Save gigenthomas/15c09bb6173e8b3c4fb6f3a213284a34 to your computer and use it in GitHub Desktop.

Select an option

Save gigenthomas/15c09bb6173e8b3c4fb6f3a213284a34 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
// Define a struct for map operations
type MapOperation struct {
Key int
Value string
}
// Worker function to handle map updates
func mapManager(ch chan MapOperation, done chan bool) {
data := make(map[int]string)
for op := range ch { // Continuously listen for incoming operations
data[op.Key] = op.Value
}
// Print the final map state after all operations
fmt.Println("Final Map:", data)
done <- true
}
func main() {
ch := make(chan MapOperation) // Channel for sending map updates
done := make(chan bool) // Channel to signal completion
wg := sync.WaitGroup{}
// Start the map manager goroutine
go mapManager(ch, done)
// Start multiple goroutines to send updates
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
ch <- MapOperation{Key: id, Value: fmt.Sprintf("Worker-%d", id)}
}(i)
}
wg.Wait() // Wait for all workers to finish
close(ch) // Close channel to signal completion
<-done // Wait for map manager to finish
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment