Page 1 of 1

Counting semaphores.... of the second kind....

Posted: Tue Apr 28, 2015 8:56 pm
by rew
We have a situation where we want to wait for something to finish. But in fact, we need N sub-parts to finish.

To implement this "neatly" I thought there was a type of counting semaphore that allows me to:

* decrement it below zero without waiting. (N times)
* the "create jobs" process then waits on the semaphore.
* the "doit" process increment it each time it finishes something.
* the "create jobs" process is woken up after N jobs have finished. i.e. after the Nth increment causes the count to reach zero again.

We now count the number of jobs externally and wait N times on the semaphore. I think this is not as neat as can be.

We could also count the number of jobs. Increment it for each job submitted, and decrement it for every job finished. The we only signal the semaphore on finishing the last job. The count now gets modified in both the job-creator, and the job-finisher, leading to race conditions. (or, requiring a critical section for updating the count). Ugly IMHO.

Is this an unusual way to use semaphores? Is there a neat way to implement this?

Re: Counting semaphores.... of the second kind....

Posted: Tue Apr 28, 2015 8:59 pm
by Giovanni
You could use events: chEvtWaitAll().

It exits only when all the specified flags are set (an AND condition).

Giovanni