Wilhelm Sorban
Wilhelm Sorban

Reputation: 1131

Do something while sem_wait in C

I am trying to avoid using sem_wait, and have something like: "While waiting for semaphore, do something". So then I found out about sem_getvalue which is supposed to return 0 in case of success.

So I initiate the semaphore with:

sem_init(&sem1, 0, 0);

And instead of

sem_wait(&sem1);

I need something like:

while(sem_getvalue(&sem1, 2) < 0){
    printf("do this\n");
}

I have no problems with sem_wait, everything seems to function properly. But with the second, I am getting Segmentation fault error during execution.

Any help is greatly appreciated, thanks!

Upvotes: 2

Views: 1940

Answers (2)

Jens Gustedt
Jens Gustedt

Reputation: 78943

You shouldn't use sem_getvalue for this since you are losing atomicity. Use sem_trywait for the task

for (;;) {
  if (sem_trywait(&sem1)) {
     if (errno != EAGAIN) {
         /* handle error */
         abort();
     }
     errno = 0;
     printf("do this\n");
  } else {
     break;
  }
}

Upvotes: 5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

sem_getvalue returns a status, and places the semaphore value at the pointer passed as the second parameter. You need to check the return status (which is zero when the function succeeds) and only then check the semaphore value, like this:

int sval1;
if (sem_getvalue(&sem1, &sval1) == 0 && sval1 < 0) {
    ...
}

Upvotes: 2

Related Questions