CORBA 2.3.3 Programmer's Guide for C++
Include the $NSD_ROOT/include/nsdevent/vthread.h header file in your program:
#include <nsdevent/vthread.h>
1.
Define a mutex:
Fw_Thread::Mutex appMutex;
2.
Enclose the critical section of codefor example, the portion of code that modifies critical datawith calls to lock() and
unlock():
appMutex.lock();
//Code to be protected goes here
appMutex.unlock();
3.
Alternatively, if needed, you can use the try_lock() method. This method attempts to lock the mutex and returns immediately
with a nonzero result if the attempt fails.
The class Fw_Thread::Preemption_Mutex is also included in $NSD_ROOT/include/nsdevent/vthread.h. This
class, which wraps Fw_Thread::Mutex with a consciousness of preemption, is a no-op on non-preemptive threading platforms
such as NonStop systems. On preemptive threading platforms (such as Unix and Microsoft Windows), this class behaves identically
to Fw_Thread::Mutex.
Creating and Using a Condition Variable
A condition variable communicates information about shared data. For example, you can use a condition variable to signal that a
queue is no longer empty, or that it has become empty, or that something else needs to be done or can be done within the shared
data manipulated by threads in an application program.
A condition variable allows a thread to start a task and then enter a waiting state until a necessary condition (performed by another
thread) is satisfied. Another thread must be written to signal the waiting thread when the condition is satisfied.
To create and use a condition variable, define an instance of the Fw_Thread::Condition_Variable class and perform the
following steps:
Include the $NSD_ROOT/include/nsdevent/vthread.h header file in your program:
#include <nsdevent/vthread.h>
1.
Define a condition variable:
Fw_Thread::Condition_Variable workDone;
2.
Enclose each critical section of code with calls to the lock() and unlock() member functions of the condition variable.
Place either the wait() or the signal() member function of the condition variable between the lock() and
unlock() function calls.
Thread 1:
appCondV.lock();
//Code to be protected
appCondV.wait();
//Code to be protected
appCondV.unlock();
Thread 2:
appCondV.lock();
//Code to be protected
appCondV.signal();
//Code to be protected
appCondV.unlock();
3.
As shown in the vthread.h file, the vthread implementation of a condition variable inherits from a mutex. Each time a vthread
Condition_Variable class is instantiated, a mutex is created and associated with a condition variable in the underlying
pthread interface. Therefore, invoking the lock() method of the Condition_Variable class is equivalent to locking the
underlying mutex. As a result, only one thread can own a condition variable at a given time. To allow other threads to compete for