GO routine never exits based on stop condition - unable to find the reason

70 Aufrufe
Direkt zur ersten ungelesenen Nachricht

Gowtham Raj

ungelesen,
28.03.2022, 11:54:1428.03.22
an golang-nuts

In this example, we have a worker. The idea here is simulate clean shutdown of all go routines based on a condition.

In this case, go routines get spun - based on workers count. Each go routine reads the channel, does some work and sends output to the outputChannel.

The main go routine reads this output and prints it. To simulate a stop condition, the doneChannel is closed. Expected outcome is that select inside each go routine will pick this up and execute return which in turn will call the defer println. The actual output is that it never gets called and main exits.

Not sure what's the reason behind this.

Code at https://go.dev/play/p/-R7Llw9X_6U 

Can you please help to figure out the bug in this code.

Sean Liao

ungelesen,
28.03.2022, 12:12:0028.03.22
an golang-nuts
1. your generator never finished
2. your work channel still has things in it, there's no guarantee select will choose done first
3. reading from a closed channel will give you a zero value


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/3762b074-63c5-407e-9515-6833465dc94en%40googlegroups.com.

Steven Hartland

ungelesen,
28.03.2022, 12:21:5328.03.22
an Gowtham Raj, golang-nuts
There is no guarantee that the select chooses the done case, so you need to check in work case as well e.g.

--

Gowtham Raj

ungelesen,
28.03.2022, 12:41:4728.03.22
an Steven Hartland, golang-nuts
Hello Steven,

Wow, this solved the problem. Never saw this pattern before. Thanks for your help !!
If you have any reference material for further reading for patterns like this can you please share them.

Regards,
Gowtham

Steven Hartland

ungelesen,
28.03.2022, 12:53:2428.03.22
an Gowtham Raj, golang-nuts
No problem, there's a nice little write up on it stackoverflow.

Gowtham Raj

ungelesen,
28.03.2022, 12:58:0328.03.22
an Steven Hartland, golang-nuts
Great, thanks! 
Allen antworten
Antwort an Autor
Weiterleiten
0 neue Nachrichten