sem_wait()-Wait for Semaphore



Syntax

#include <semaphore.h>

int sem_wait(sem_t * sem);


Threadsafe: Yes

The sem_wait() function decrements by one the value of the semaphore. The semaphore will be decremented when its value is greater than zero. If the value of the semaphore is zero, then the current thread will block until the semaphore's value becomes greater than zero.

Parameters

sem
(Input) A pointer to an initialized unnamed semaphore or opened named semaphore.

Authorities

None

Return Value

0
sem_wait() was successful.
-1
sem_wait() was not successful. The errno variable is set to indicate the error.

Error Conditions

If sem_wait() is not successful, errno usually indicates one of the following errors. Under some conditions, errno could indicate an error other than those listed here.

[EINTR]
Interrupted function call.

[EINVAL]
The value specified for the argument is not correct.

A function was passed incorrect argument values, or an operation was attempted on an object and the operation specified is not supported for that type of object.

An argument value is not valid, out of range, or NULL.

Error Messages

None.

Related Information

Example

The following example creates a semaphore with an initial value of 10. The value is decremented by calling sem_wait().

#include <stdio.h>
#include <semaphore.h>
main() {
  sem_t my_semaphore;
  int value;

  sem_init(&my_semaphore, 0, 1);
  sem_getvalue(&my_semaphore, &value);
  printf("The initial value of the semaphore is %d\n", value);
  sem_wait(&my_semaphore);
  sem_getvalue(&my_semaphore, &value);
  printf("The value of the semaphore after the wait is %d\n", value);
}

Output:

The initial value of the semaphore is 1
The value of the semaphore after the wait is 0


Top | Interprocess Communication APIs | APIs by category


[Information Center Home Page | Feedback ] [Legal | AS/400 Glossary]