package main import ( "fmt" "sync" "time" ) // worker listens for a signal to stop or react to an event func worker(id int, stopChan <-chan struct{}, wg *sync.WaitGroup) { defer wg.Done() fmt.Printf("Worker %d: Waiting for signal... ", id) select { case <-stopChan: // Channel closure sends a zero value fmt.Printf("Worker %d: Signal received! Shutting down. ", id) case <-time.After(5 * time.Second): fmt.Printf("Worker %d: Timeout reached, no signal. ", id) } } func main() { stopSignal := make(chan struct{}) // Unbuffered channel var wg sync.WaitGroup numWorkers := 3 for i := 1; i <= numWorkers; i++ { wg.Add(1) go worker(i, stopSignal, &wg) } // Simulate some work before sending the signal time.Sleep(2 * time.Second) fmt.Println("Main: Sending shutdown signal to all workers...") close(stopSignal) // Close the channel to broadcast the signal wg.Wait() fmt.Println("Main: All workers have processed the signal.") }