Resolve deadlock

Not sure why there’s a deadlock, even though the channel was closed, and i looped the amount of times needed


import (
	"fmt"
	"time"
)

func sth() {

	ticker := time.NewTicker(500 * time.Millisecond)

	done := make(chan bool)
	c := make(chan int)

	go func() {
		for i := 0; i < 10; i++ {
			select {
			case <-done:
				return
			case <-ticker.C:
				c <- i
			}
		}
		close(c)
	}()

	for i := 0; i < 10; i++ {
		fmt.Println(<-c)
	}
	

	time.Sleep(1 * time.Second)
	ticker.Stop()
	done <- true
	fmt.Println("Ticker stopped")
}

func main() {
	sth()
}

Thats the full code.
Heres the link - https://play.golang.org/p/tQGt2rOQX3U

Before executing the line done <-true, channel c and Ticker are both closed (ended) so this line blocks and try to transfer control to another task but there is none so that’s the reason you got the message “all goroutines are asleep”

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.