JAVA-BASED REAL-TIME PROGRAMMING
JAVA-BASED REAL-TIME PROGRAMMING
JAVA-BASED REAL-TIME PROGRAMMING
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
3.2. Resources and mutual exclusion – Semaphores<br />
queue depends on the scheduling of that particular run-time system. Normally,<br />
threads are ordered according to priority, and equal priority threads<br />
are placed in the order they arrived (FIFO).<br />
Supporting timeout<br />
In addition to the core methods, for convenience, the following method (return<br />
type boolean) is also defined:<br />
tryTake(long timeout) The same as take, but the caller gives up taking<br />
the semaphore after timeout milliseconds. If the semaphore was taken,<br />
true is returned. Otherwise false is returned.<br />
Using this method requires some care. First, there is no guarantee that the<br />
caller is unblocked exactly after the timeout time, it can be later (but not<br />
earlier). The release time may depend on what other threads that have issued<br />
blocking calls with timeouts, the CPU load, etc. Thus, the same type of<br />
problems as with the Thread.sleep method.<br />
Secondly, the returned boolean value must be taken care of (which is not<br />
checked by the compiler in Java, just like in C/C++/C#). If false is returned,<br />
perhaps after a long time of operation, and not considered due to a<br />
programming error, shared resources can by accident be accessed without mutual<br />
exclusion. The name tryTake, instead of overloading on take for instance,<br />
is selected to emphasis the characteristics of the operation.<br />
Finally, consider if your design is right if you use the tryTake operation.<br />
It should be used instead of implementing additional timer threads, but not<br />
for cyclic polling of the semaphore value. Some systems provide a way of<br />
polling the value without actually trying to take the semaphore. Since such a<br />
method easily could be misused by unskilled programmers, such a method is<br />
not provided here.<br />
Semaphores in other systems<br />
When proposed by Dijkstra, the original name of the take operation was P,<br />
from the Dutch word Passeren, referring to the situation that the thread wants<br />
to Pass. The original name of the give operation was V, from Vrijgeven,<br />
referring to the release (’free-giving’) of the resource. The names P and V are<br />
still used in many systems today.<br />
The most common names for take and give are wait and signal, respectively.<br />
These names are more expressive and relates well to the English terms<br />
used for railroad semaphores. The semaphore concept actually originates from<br />
railroad traffic, where the tracks are the resources. As we will see later, wait<br />
is not a useful name for a semaphore method in Java since it already is a final<br />
method (with another meaning) in class Object.<br />
57