using goroutine to implement a command control?

61 views
Skip to first unread message

Bill Yan

unread,
Oct 17, 2011, 9:21:20 PM10/17/11
to golan...@googlegroups.com
Hello guys,

I am working on a program which fetches data from the internet. But while it's running, I want to have a command control. My idea is to have two different goroutines, the first one accepts command, and write to a channel. The second one looks at the channel see if there is a command, and reacts accordingly. The thing is, a goroutine always blocks at "checking channel".

I don't want the second goroutine be blocked. I want it keep working on the task if there is no command, and check the channel again, see if there is a new command. if there is no new command, run the next task. 

Is this doable?

Andrew Gerrand

unread,
Oct 17, 2011, 9:39:01 PM10/17/11
to golan...@googlegroups.com
You can do a non-blocking channel read like so:

  v, ok := <-ch

"ok" is a boolean that indicates whether a receive occurred.

Andrew

Ian Lance Taylor

unread,
Oct 18, 2011, 12:01:00 AM10/18/11
to golan...@googlegroups.com
Andrew Gerrand <a...@golang.org> writes:

That's the old way. Now a channel receive always blocks. The "ok"
value is false if a zero value was received because the channel is
closed.

To do a non-blocking channel read today you need to write

select {
case v = <-ch:
// Do something with v.
default:
}

The OP probably wants to check both channels in a single select
statement.

Ian

Andrew Gerrand

unread,
Oct 18, 2011, 12:47:29 AM10/18/11
to golan...@googlegroups.com


On Tuesday, October 18, 2011 3:01:00 PM UTC+11, Ian Lance Taylor wrote:
Andrew Gerrand <a...@golang.org> writes:

> You can do a non-blocking channel read like so:
>
>   v, ok := <-ch
>
> "ok" is a boolean that indicates whether a receive occurred.

That's the old way.  Now a channel receive always blocks.  The "ok"
value is false if a zero value was received because the channel is
closed.

Gosh, you're right, of course. Sorry for the misinformation.

Andrew "looking forward to Go 1" Gerrand ;-)

Reply all
Reply to author
Forward
0 new messages