Drain channel on demand without busy looping?

326 views
Skip to first unread message

cpu...@gmail.com

unread,
Feb 5, 2023, 4:12:33 PM2/5/23
to golang-nuts
I have the requirement of being able to drain a channel, i.e. make sure that downstream processes all data currently being sent. One possible pattern is something like

for{
select{
case <-q.data:
default:
}
}

where the default branch could indicate that channel has been drained. My concern is, that this would create a busy loop on the default branch even when not trying to drain the channel.

I could use an atomic for checking if work should be done in default (i.e. signal channel has been drained).

Would that still busy-loop? Are there better patterns?

Cheers,
Andi

Jan Mercl

unread,
Feb 5, 2023, 4:20:42 PM2/5/23
to cpu...@gmail.com, golang-nuts
On Sun, Feb 5, 2023 at 5:12 PM cpu...@gmail.com <cpu...@gmail.com> wrote:

> Would that still busy-loop? Are there better patterns?

for range q.data {}

iff the sending side properly closes the channel.

Jason E. Aten

unread,
Feb 8, 2023, 1:38:28 AM2/8/23
to golang-nuts

I have the requirement of make sure that downstream processes all data currently being sent. 

I usually have the client submit a Request struct the includes a new Done channel. When the downstream goroutine
finishes processing a given Request r, they close the r.Done channel. The client can wait or select on the r.Done channel to
know when processing is finished.
 

Andreas Götz

unread,
Feb 8, 2023, 8:16:01 AM2/8/23
to golang-nuts
Thanks Jason,

that is absolutely beautiful. Ranging over channel wont work when the channel remains open (my case), but the "callback" pattern is really nice.

Much appreciated,
Andi

Reply all
Reply to author
Forward
0 new messages