Advertisement
betrayed

thread_for_duration.go

May 19th, 2024
614
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.30 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "os"
  6.     "os/signal"
  7.     "syscall"
  8.     "sync"
  9.     "time"
  10. )
  11.  
  12. func worker(id int, wg *sync.WaitGroup, stopChan chan struct{}) {
  13.     defer wg.Done()
  14.     for {
  15.         select {
  16.         case <-stopChan:
  17.             fmt.Printf("Worker %d received stop signal. Exiting...\n", id)
  18.             return
  19.         default:
  20.             fmt.Printf("Worker %d is running\n", id)
  21.             time.Sleep(1 * time.Second)
  22.         }
  23.     }
  24. }
  25.  
  26. func main() {
  27.     fmt.Println("Press CTRL+C to exit")
  28.  
  29.     // Create a channel to listen for the interrupt signal
  30.     interrupt := make(chan os.Signal, 1)
  31.     signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
  32.  
  33.     // Create a wait group to wait for all goroutines to finish
  34.     var wg sync.WaitGroup
  35.  
  36.     // Create a channel to signal stop to goroutines
  37.     stopChan := make(chan struct{})
  38.  
  39.     // Start 5 goroutines
  40.     for i := 0; i < 5; i++ {
  41.         wg.Add(1)
  42.         go worker(i, &wg, stopChan)
  43.     }
  44.  
  45.     // Wait for the interrupt signal
  46.     <-interrupt
  47.     fmt.Println("Interrupt signal received. Stopping workers...")
  48.  
  49.     // Signal stop to goroutines
  50.     close(stopChan)
  51.  
  52.     // Wait for all goroutines to finish before exiting
  53.     wg.Wait()
  54.     fmt.Println("All workers have exited. Exiting program.")
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement