Context:
I am trying to have two processes writing to the same array in the shared memory space.
Each process will write half of the array with a for loop.
The first element of the array will always store the index of the next element to be written.
IPC is done through a semaphore in the shared memory.
Preconditions:
- Both the array and semaphore are properly set up in the shared memory.
- The programme works fine if I wait sem_wait and sem_post outside of the for loop, meaning make the whole process atomic. (This is also the reason why I believe the semaphore and array has been set up properly)
Problem
However, when I try to reduce the critical region by putting sem_wait and sem_post into the for loop. It is not sync as there are part of the array which are not written. But the two processes finished their loops where the total loop counts should be equal to the array length.
Many thanks to suggestions why this happens???
UPDATE
On OS X, sem_init() is not working as expected. Used sem_open() to solve the problem. Reference: http://lists.apple.com/archives/darwin-dev//2008/Oct/msg00044.html