Locking semaphores in C problem sys/sem
Posted
by Vojtech R.
on Stack Overflow
See other posts from Stack Overflow
or by Vojtech R.
Published on 2010-04-29T16:32:26Z
Indexed on
2010/04/29
22:37 UTC
Read the original article
Hit count: 427
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
© Stack Overflow or respective owner