Default in select running thrice every time even when the channel is returned

import "fmt"
import "time"

func ab(ch chan bool,i int) {
	duration := time.After(time.Second * time.Duration(600))
	for {
		select {
		case <- duration:
			fmt.Printf(" received value: %d ",i)
			break
		default:
			fmt.Printf(" no value received %d ",i)
			ch <- true
			break
		}
	}
}

func main() {
	for i := 1; i < 10; i++{
		fmt.Printf("Testcase %d start",i)
		ch := make(chan bool, 1)
		go ab(ch,i)
		if <- ch {
			fmt.Printf("Testcase %d end",i)
		}
	fmt.Printf("sleeping for 10 seconds")
	time.Sleep(10*time.Second)
	}
}```

can anyone suggest why it is printing thrice rather than once

Because you have a buffered channel.

It can hold 1 item. The first time it gets hit it prints and then sends. That is read immediately in the main goroutine. And the channel is free again.

Next time the loop runs is again printed and sent. Nothing reads from the channel now, so it is full.

Third iteration happens now. Again printing happens, then the ab-goroutine blocks as the channel is full.

What you probably want is to break from the fir not from the select. You need to apply a label to for and break to do so

1 Like

Thank you for the reply , I got the concept now , return instead of break works here

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