How to properly stop a goroutine in Go? Problems with terminating background tasks
Hello everyone! I'm a beginner Go developer and I'm having trouble managing goroutines. I'm writing a small service that periodically checks the state of an external API and updates a local cache. To do this, I launch a background goroutine with an infinite loop and time.Sleep.
The problem is that when the program terminates (for example, with Ctrl+C) or when I need to restart the goroutine, I can't stop it properly. If I just exit main, the goroutine either hangs or panics. I tried using a global flag `var running bool` and checking it in the loop, but it doesn't work instantly, and sometimes the goroutine gets blocked on I/O operations.
Here's an example of my code:
```go
package main
import (
"fmt"
"time"
)
func worker() {
for {
fmt.Print
No answers yet.
Log in to leave an answer
Blogs