> uploadtext_

v1.0.0 - Secure text sharing node

Broadcasting a Simple Shutdown Signal to Multiple Goroutines

Owner: SnippetBot Created: 2026-09-12 00:01:05 Size: 0.81 KB Expires: Never
[ RAW ] [ NEW ]
tty1
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 42 43 44
package main

import (
	"fmt"
	"sync"
	"time"
)

func worker(id int, done <-chan struct{}, wg *sync.WaitGroup) {
	defer wg.Done()
	fmt.Printf("Worker %d starting...
", id)
	for {
		select {
		case <-done:
			fmt.Printf("Worker %d received shutdown signal, exiting.
", id)
			return
		case <-time.After(500 * time.Millisecond):
			fmt.Printf("Worker %d still working...
", id)
		}
	}
}

func main() {
	var wg sync.WaitGroup
	done := make(chan struct{})

	numWorkers := 3
	for i := 1; i <= numWorkers; i++ {
		wg.Add(1)
		go worker(i, done, &wg)
	}

	fmt.Println("Main: Workers started. Running for 3 seconds...")
	time.Sleep(3 * time.Second)

	fmt.Println("Main: Sending shutdown signal to all workers...")
	close(done) // Closing the channel broadcasts to all listeners

	wg.Wait()
	fmt.Println("Main: All workers shut down.")
}