Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "os"
- "os/signal"
- "syscall"
- "sync"
- "time"
- )
- func worker(id int, wg *sync.WaitGroup, stopChan chan struct{}) {
- defer wg.Done()
- for {
- select {
- case <-stopChan:
- fmt.Printf("Worker %d received stop signal. Exiting...\n", id)
- return
- default:
- fmt.Printf("Worker %d is running\n", id)
- time.Sleep(1 * time.Second)
- }
- }
- }
- func main() {
- fmt.Println("Press CTRL+C to exit")
- // Create a channel to listen for the interrupt signal
- interrupt := make(chan os.Signal, 1)
- signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
- // Create a wait group to wait for all goroutines to finish
- var wg sync.WaitGroup
- // Create a channel to signal stop to goroutines
- stopChan := make(chan struct{})
- // Start 5 goroutines
- for i := 0; i < 5; i++ {
- wg.Add(1)
- go worker(i, &wg, stopChan)
- }
- // Wait for the interrupt signal
- <-interrupt
- fmt.Println("Interrupt signal received. Stopping workers...")
- // Signal stop to goroutines
- close(stopChan)
- // Wait for all goroutines to finish before exiting
- wg.Wait()
- fmt.Println("All workers have exited. Exiting program.")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement