Search code examples
c++cunixsemaphorebarrier

Making a gather/barrier function with System V Semaphores


I'm trying to implement a gather function that waits for N processes to continue.

struct sembuf operations[2];

operaciones[0].sem_num = 0; 
operaciones[0].sem_op = -1; // wait() or p()

operaciones[1].sem_num = 0; 
operaciones[1].sem_op = 0; // wait until it becomes 0

semop ( this->id,operations,2 );

Initially, the value of the semaphore is N.

The problem is that it freezes even when all processes have executed the semop function. I think it is related to the fact that the operations are executed atomically (but I don't know exactly what it means). But I don't understand why it doesn't work.

Does the code subtract 1 from the semaphore and then block the process if it's not the last or is the code supposed to act in a different way?


Solution

  • It's hard to see what the code does without the whole function and algorithm. By the looks of it, you apply 2 action in a single atomic action: subtract 1 from the semaphore and wait for 0. There could be several issues if all processes freeze; the semaphore is not a shared between all processes, you got the number of processes wrong when initiating the semaphore or one process leaves the barrier, at a later point increases the semaphore and returns to the barrier. I suggest debugging to see that all processes are actually in barrier, and maybe even printing each time you do any action on the semaphore (preferably on the same console).

    As for what is an atomic action is; it is a single or sequence of operation that guarantied not to be interrupted while being executed. This means no other process/thread will interfere the action.