Re: [Vala] Question about a basic coroutine example



On Thu, Jul 7, 2011 at 9:35 PM, Serge Hulne <serge hulne gmail com> wrote:
In the snippet hereunder, I  expected the respective value of the argument
of the sleep() method, in the methods foo0() and foo1(), to have an
influence on which one of said coroutines completes first.

There are 2 flaws in your example.

1. As said Luca Bruno, coroutines are cooperative.
In your example, foo1 acts in a cooperative manner only once, at the
beginning, with the yield.
It does not act cooperatively in the loop, where it prints messages.
It does not act cooperatively in the sleep, either. (see flaw number 2)
The same goes for foo2.

2. The sleep function from posix, tells the O.S. to put to sleep the
entire process, not just one function.
If you want a function similar to "sleep" that acts in a cooperative
manner you should create a function that goes something like this:

async void coop_sleep(int s)
{
  int ms = s * 1000;
  for (int i = 0; i < ms; i++)
  {
    Idle.add(coop_sleep.callback);
    yield;
    Posix.usleep(1000);
  }
}

That is:
 * put the entire process to sleep for small periods (1000
microseconds = 1 millisecond)
    you need this, otherwise you'll have a cpu hogging application
 * pass the schedule (yield)
 * repeat for the needed times, or until a certain time arrives.

Once again, if you really need a cooperative multitasking in your app
(which by the way is not bad, unlike the cooperative multitasking in
the entire operating system that was m$ windows 3.11) you should
consider to give a try to GNU Pth. Otherwise, use threads.

--Luca



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]