To implement a concurrent timer using channels and sync in Golang, you can follow these steps:
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
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
}()
}
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
}
}
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")
}
}
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.