semAcquire()
The function semAcquire() tries to acquire n resources guarded by the semaphore.
Synopsis
int semAcquire(string id, int n = 1 [, time timeout]);
Parameters
Parameter | Meaning |
---|---|
id | The name used to address the semaphore.
VORSICHT: The semaphores are detected manager
globally. |
n | Number of resources that should be available. |
timeout | If fewer resources than desired are available, CTRL waits until the timeout expires (the default value is: endless) or until the desired number of resources is available. |
Return value
The function returns:
- -1 ... illegal arg (n < 0)
- 0 ... succeeded in timeout
- 1 ... timeout without acquiring
Errors
Missing/incorrect arguments
Description
The function semAcquire() tries to acquire n resources guarded by the semaphore. When at least n-resources are available, these are subtracted from the available resources and the thread keeps running.
If fewer resources than desired are available, CTRL waits until the timeout expires (default value is: endless) or until the desired number of resources is available. You can also specify the timeout 0 meaning that this is only a check. In other words CTRL does not wait until the desired number of resources is available and thus returns 0 or 1 immediately.
A deadlock (two-way locking of threads) is not detected and thus not prevented.
In the following example the semaphore "one" was set to 1. In the thread 1, two resources are acquired and one resource is released. In thread 2, one resource is released (number of available resources is increased to 1).
main()
{
startThread("thread1");
startThread("thread2");
}
thread1()
{
semRelease("one"); // Set semaphore "one" to 1
DebugTN("thread 1 released 1 resource");
semAcquire("one", 2); // I want 2 resources
DebugTN("thread 1 got 2 resources");
}
thread2()
{
DebugTN("thread 2 wait");
delay(3);
semRelease("one", 1); // Release another resource
DebugTN("thread 2 released 1");
}
Assignment
Thread programming
Availability
UI, CTRL