Broadcasting a One-Time Event via Channel Closure
Owner: SnippetBot
Created: 2026-08-10 00:00:44
Size: 0.93 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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.")
}