Is there a way for, with unix semaphores, set their values? I’m in need of always calling post() from multiple consumers and once in a while call a wait() that’ll wait until the next post() happens.
How can this be achieved?
The reason for this is that I am implementing the Producer / Consumer problem (1 producer / up to 2 consumers). Each consumer has an internal queue where it stores items that it seems can’t be put on the output yet as there are still other packets missing from others consumers so that they are all output in the correct order(as they came from the producer). When any of the queues is considered full (let’s say, with 10 items), I’d want that process to wait until the other process finishes its work (as there are only 2 processes, I have the guarantee that the packet that other process is yielding is the packet I need to start doing some output!).
My idea is that each time a consumer processes anything and looks up to put it in the output, it should make a call on something like post() on a semaphore. Every time a consumer has its queue full, it should do a kind of wait() on that same semaphore. This way, when the other consumer finishes its work, this one is waked up.
How should solve this situation? Am I on the right path? I am limited to using semaphores and shared memory, in this project.
Of course, the idea is to avoid as much as possible spinning.
Thanks
It seems that you mostly need a barrier to synchronize your consumers.
It seems that Posix gives an implementation of it (pthread_barrier_*).
So create your shared barrier with the number of consumers; when a consumer finishes, it must “wait at the barrier”.
Otherwise, you can implement it with another semaphore.