Locking semaphores in C problem sys/sem
- by Vojtech R.
Hi,
I have problem with my functions. Sometimes two processes enter into critical section. I can't find problem in this after I spent 10 hours by debugging. On what I should aim?
// lock semaphore
static int P(int sem_id)
{
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = -1; /* P() */
sem_b.sem_flg = 0;
if (semop(sem_id, &sem_b, 1) == -1) {
print_error("semop in P", errno);
return(0);
}
return(1);
}
// unlock semaphore
static int V(int sem_id)
{
struct sembuf sem_b[1];
sem_b.sem_num = 0;
sem_b.sem_op = 1; /* V() */
sem_b.sem_flg = 0;
if (semop(sem_id, &sem_b, 1) == -1) {
print_error("semop in V", errno);
return(0);
}
return(1);
}
The action loop:
int mutex;
if ((mutex=semget(key, 1, 0666))>=0) {
// semaphore exists
}
while(1) {
P(mutex);
assert(get_val(mutex)==0);
(*action)++;
V(mutex);
}
Many thanks