How to implement a concurrent timer using channels and sync in Golang?

To implement a concurrent timer using channels and sync in Golang, you can follow these steps:

  1. Create a package-level variable of type chan bool to represent the timer channel and a variable to indicate if the timer is active.
var timerChan = make(chan bool) var isTimerActive bool
  1. Define a startTimer function that takes the duration of the timer as an argument.
func startTimer(duration time.Duration) { fmt.Println("Timer started") isTimerActive = true // Start a goroutine that waits for the specified duration and then writes to the timer channel to signal completion go func() { <-time.After(duration) timerChan <- true }() }
  1. Define a stopTimer function that stops the timer if it is active.
func stopTimer() { if isTimerActive { fmt.Println("Timer stopped") // Write to the timer channel to signal completion timerChan <- true } }
  1. Implement a function main to test the timer functionality.
func main() { // Start the timer for 3 seconds startTimer(3 * time.Second) // Use a select statement to wait for any of the timer completion or interrupt signal from the user select { case <-timerChan: fmt.Println("Timer completed") case <-interruptChan: fmt.Println("Timer interrupted") } }
  1. Run the program, and it will start the timer for 3 seconds. If the timer completes before any interruption, it will print "Timer completed". If there is an interruption, it will print "Timer interrupted".
go run main.go

Note: In this example, we assume that the interruptChan represents an interrupt signal from the user, which could be implemented using another goroutine watching for user input.