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. Multi-Threaded Programming<br />
public void take() Causes the calling thread to block until the counter that<br />
represents this semaphore obtains a positive value. On return the counter,<br />
named count below, is decremented by one. Basically this means executing<br />
the following code atomically (as for give):<br />
while (count{\textless}1) wait(); // wait() suspends until notified.<br />
--count; // Or set to false for a binary sem.<br />
public boolean tryTake(long timeout) Causes the calling thread to block<br />
until the counter that represents this semaphore obtains a positive value<br />
(just like the ordinary take method) or until the timeout time has passed.<br />
If, due to other threads calling give, the semaphore is possible to take,<br />
but the caller of take is not rescheduled for execution until after the<br />
timeout time after its call of take, it is considered as a timeout and<br />
hence false is returned (and the internal state of the semaphore is left<br />
unchanged).<br />
Note that the semaphore operations are not ordinary methods; they have to<br />
utilize some type of system call to suspend and resume execution. That is,<br />
when take results in suspended execution as mentioned in the comment above,<br />
the thread is no longer ready for execution and the scheduler of the operating<br />
system (or JVM if so called green threads are used) puts the thread (in terms<br />
of data including the context) in the waiting queue of the semaphore. Hence,<br />
the thread consumes no CPU time while being blocked. The mentioned system<br />
call can be a native semaphore operation (when semaphores are supported by<br />
the OS). When using a JVM, the system call is accomplished by the use of<br />
synchronized (explained below).<br />
Semaphore classes<br />
The classes implementing the Semaphore interface, and their motivation, are<br />
as follows:<br />
BinarySem A Semaphore containing a boolean flag instead of a counter, to<br />
support signaling in cases when waiting threads should not catch up<br />
with successive missed calls of give. In the default Java implementation<br />
a boolean is used to keep the state of the semaphore. Native mappings<br />
can use that, or a bit, or a counter with a maximum value of one as in<br />
win32.<br />
CountingSem Basic type of semaphore containing a counter which is incremented<br />
by one for each call to give, and decremented by one for each<br />
returning call of take. A typical signaling example using this type of<br />
semaphore was shown in Figure 3.2.<br />
64 2012-08-29 16:05