sem_trywait()--Try to Decrement Semaphore
Syntax
#include <semaphore.h> int sem_trywait(sem_t * sem);
Service Program Name: QP0ZPSEM
Default Public Authority: *USE
Threadsafe: Yes
The sem_trywait() function attempts to decrement the value of the semaphore. The semaphore will be decremented if its value is greater than zero. If the value of the semaphore is zero, then sem_trywait() will return -1 and set errno to EAGAIN.
Parameters
- sem
- (Input) A pointer to an initialized unnamed semaphore or opened named semaphore.
Authorities
None.
Return Value
| 0 | sem_trywait() was successful. |
| -1 | sem_trywait() was not successful. The errno variable is set to indicate the error. |
Error Conditions
If sem_trywait() is not successful, errno usually indicates one of the following errors. Under some conditions, errno could indicate an error other than those listed here.
- [EAGAIN]
-
Operation would have caused the process to be suspended.
The value of the semaphore is currently zero and cannot be decremented.
- [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
- The <semaphore.h> file (see
Header Files for UNIX®-Type Functions)
- sem_close()--Close Named Semaphore
- sem_destroy()--Destroy Unnamed Semaphore
- sem_getvalue()--Get Semaphore Value
- sem_init()--Initialize Unnamed Semaphore
- sem_init_np()--Initialize Unnamed Semaphore with
Maximum Value
- sem_open()--Open Named Semaphore
- sem_open_np()--Open Named Semaphore with Maximum
Value
- sem_post()--Post to Semaphore
- sem_post_np()--Post Value to Semaphore
- sem_unlink()--Unlink Named Semaphore
- sem_wait()--Wait for Semaphore
- sem_wait_np()--Wait for Semaphore with Timeout
Example
The following example attempts to decrement a semaphore with a current value of zero.
Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
#include <stdio.h>
#include <errno.h>
#include <semaphore.h>
main() {
sem_t my_semaphore;
int value;
int rc;
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);
rc = sem_trywait(&my_semaphore);
if ((rc == -1) && (errno == EAGAIN)) {
printf("sem_trywait did not decrement the semaphore\n");
}
}
Output:
The initial value of the semaphore is 1 The value of the semaphore after the wait is 0 sem_trywait did not decrement the semaphore
API introduced: V4R4