Name

sem_wait, sem_trywait
sem_trywait

- decrement (lock) a semaphore

Library

libpthread.lib

Synopsis

  #include <semaphore.h>
  int sem_wait (sem_t *sem);
  int sem_trywait (sem_t *sem);

Return values

Upon successful completion, the value 0 is returned; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

The sem_wait function decrements (locks) the semaphore pointed to by sem, but blocks if the value of sem is zero, until the value is non-zero and the value can be decremented.

The sem_trywait function decrements (locks) the semaphore pointed to by sem only if the value is non-zero. Otherwise, the semaphore is not decremented and an error is returned.


Examples

sem_t psem;   
if (sem_init(&psem, 0, 1) < 0) {
        perror("sem_init");
        return -1;
   }
 /* Lock Semaphore */
if( sem_wait(psem) == -1 ) {
  perror("sem_wait failed");
  return -1;
}
else
    printf ("Locked successfully\n");


sem_t psem;   
if (sem_init(&psem, 0, 1) < 0) {
        perror("sem_init");
        return -1;
   }
 /* Lock Semaphore */
if ( sem_trywait(psem) == 0)
{   switch(errno)
     {
     case 0:
        printf ("Locked successfully\n");
        break;
    case EAGAIN:
        printf ("could not lock, try later.....\n");
        break;
    }
}
else
    printf ("Sem_trywait failed \n");


Errors

The sem_wait and sem_trywait functions will fail if:
[EINVAL]
  The sem argument points to an invalid or uninitialized semaphore.

Additionally, sem_trywait will fail if:
[EAGAIN]
  The semaphore value was zero, and thus could not be decremented.


See also

sem_getvalue, sem_post


Feedback

For additional information or queries on this page send feedback

© 2008 Nokia Corporation. All rights reserved. This documentation can be used in the connection with this Product to help and support the user.

Top