There are many options for this, depending on what you're actually trying
to achieve.
For instance, you could have a waitgroup (from the sync package) shared
between all producer and consumer goroutines, i.e those writing to and
reading from the channel. Producers add to the waitgroup before writing,
consumers mark a task as done after reading and processing a node. When the
tree has been fully parsed and the waitgroup task count gets to zero, a
goroutine blocking on waitgroup.Done() can then close the channel, causing
the for loop to end.

That's a very basic approach, anyway. Look more into concurrent programming
basics online.

On Mon, Jun 8, 2026, 13:34 'andreas graeper' via golang-nuts <
[email protected]> wrote:

> hi. thanks for your answers. i understand that the channel has to be
> closed. what i do not understand is the error 'write after close'
> if w (called from w0) was executed in another thread, than i had to wait
> for the end of w by some mean of synchronization, before i close the
> channel. but if w0 and w are executed in same thread they are executed
> sequentielly inside the thread and close inside w0 is called when w has
> returned. so it should be fine. in main then for v := range c { } would
> end.
>
> andreas graeper schrieb am Montag, 8. Juni 2026 um 11:42:37 UTC+2:
>
>> hi. i try to walk through a tree putting elems into channel
>> w(t,c) { if t!=nil { w(t.left,c) ; c<-t.elem ; w(t.right,c) }}
>> w0(t,c) { w(t,c); close(c); }
>> main(){
>>  go w0(t,c)
>>  for e := range c {}
>> }
>> if i drop 'close(c)' i get 'all threads dead' , otherwise 'write after
>> close'
>> it feels as if w is send to background too and i have to sync to the end
>> of w before i close the channel ?
>> thanks in advance, andi
>>
> --
> 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 [email protected].
> To view this discussion visit
> https://groups.google.com/d/msgid/golang-nuts/8b343e2a-ab29-4c33-8f3f-beb5b61ae09dn%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/8b343e2a-ab29-4c33-8f3f-beb5b61ae09dn%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
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 [email protected].
To view this discussion visit 
https://groups.google.com/d/msgid/golang-nuts/CADgY6e-noOWvVSVugLzXL%3DwpaRvfBJFmkOB-_mbx%3Dub0OFKdHQ%40mail.gmail.com.

Reply via email to