It would involve counting how many goroutines are capable of running
at a particular moment. The idle goroutine starts running if the
counter drops to 0. If the idle goroutine is running, it would need to
periodically check whether the counter is still 0 and voluntarily
suspend itself as soon as it determines the counter is non-zero.
There is no simple answer how to count the number of goroutines that
are running. If a goroutine is sending through a channel, it would
first need to make sure that the send is non-blocking. If the send
blocks the sender, it decrements the counter and goes to sleep. The
receiver would have to notify the sleeping senders, so that they can
retry the send procedure. The receiver needs to decrement the
counter if a channel receive would block, and then needs to go sleep.
A sender would have to notify the sleeping receivers, so that they can
retry the receive procedure. The counter is incremented when a
sender or receiver starts running.
In addition, the counter is modified when a goroutine is waiting
because of an OS call. Same in respect to CGO calls. Handling the
counter in these cases means to *predict* whether the OS/CGO call will
block, the prediction needs to be made before the call is executed. It
effectively amounts to at least one of the following: (1) to control
the access to OS calls and CGO functions (some kind of encapsulation,
and some kind of access policy), and (2) building a sufficiently
accurate emulator/tracker of the called OS and CGO functions. The
problem is that each OS/CGO call is unique (well, they fall into
categories, so in fact those categories are unique), and each category
requires a separate implementation in the encapsulation layer or in
the emulator/tracker. Not to mention, the interactions of multiple OS/
CGO calls can be very complex (ok, they can be made simpler by
intentionally disallowing certain types of interactions, but such
simplifications have their consequences: lower performance in the
better case, and a loss of functionality in the worse case).
... so, this is basically what I meant when I wrote that "it is doable
in Go if you program it by hand".
A question is whether the problem you are solving actually needs the
"idle goroutine" or not.
On May 3, 10:36 am, Sunil S Nandihalli <
sunil.nandiha...@gmail.com>
wrote:
> I realize there is no one line go code .. can you probably define a pattern
> of code which would make this happen...
>