Using POSIX Semaphores to divide work in Parent and Child Processes
Hi, I'm learning about semaphores and I'm trying to implement a programme where parent and child processes each have to perform an action N number of times. Here's what I did so far:
1. Init two shared semaphores, fill, and unfill
Init one semaphore, mutex, that is not shared
2. Initial values are, fill=S(1), unfill=S(0), mutex=S(1)
3. Created a shared array, where the processes will perform actions (this 'action' is meant to be the critical section, which has to be protected)
And I've arranged the semaphores in the following way so that
1. Each process will wait for the other until they can do the action with the sharedArray (the outer sem_wait and sem_post), and
2. Within each process, only one process can do the action at a time (hence the mutex)
But I am not getting an equal share of N actions for both the Parent and the Child. Can someone please help me out?
Code:
result = fork(); if (result){
for(i = 0; i < N; i ++){
sem_wait(fill);
sem_wait(mutex);
// do something to sharedArray;
sem_post(mutex);
sem_post(unfill);
}
} else { //Child
for(i = 0; i < N; i ++){
sem_wait(unfill);
sem_wait(mutex);
// do something to sharedArray;
sem_post(mutex);
sem_post(fill);
}
Thanks!