1. System Configuration -
Header files & Compiler Directives
2. Thread Object
3. Event Object
The PiThreads library defines the
class Event to provide event synchronization services. The class Event is defined in the header
file event.h, which must be included after the inclusion of the thread.h header
file and the #define WIN or #define POSIX statement. The PiThreads event object can be instantiated as either a
manual-reset event or an automatic-reset event. A thread which attempts to wait on an event object is blocked if
the event is in a non-signaled state, and permitted to continue when the event
reaches a signaled state. The public
member functions which serve as the interface to the event object can be seen
below.
class Event
{
public:
Event();
Event(bool Manual_Reset);
void Signal();
void Reset();
void Pulse();
void Wait();
~Event();
};
An automatic-reset is instantiated
with the default constructor, a manual event is instantiated by passing a value
of true to the overloaded constructor Event(bool Manual_Reset). As noted above, a thread calls the Wait()
member function to wait on an event.
Signal() and Pulse() are used to release waiting threads, the semantics
of Signal() and Pulse() differ depending on whether an automatic-reset or
manual-reset event has been instantiated.
Table 4 on the following page describes the behavioral differences
between calls to Pulse() and Signal() between automatic-reset and manual-reset
events.
|
Signal() |
Pulse() |
Automatic-Reset
|
If
threads are waiting on the event, |
If any threads are waiting on the event
|
Manual-Reset |
All
threads waiting on the event |
All
threads waiting on the event |
The following code instantiates a manual-reset event,
an automatic-reset event, and threads to wait on each.
//#define WIN or POSIX
Event Auto;
Event Manual(true);
class ThreadDemo : public
Thread
{
public:
ThreadDemo() : Thread() {}
void EntryRoutine(void)
{
Auto.Wait();
cout << “Released from automatic reset event” <<
endl;
}
void ExitRoutine(void)
{
Manual.Wait();
cout << “Released from manual-reset event” << endl;
}
};
void main()
{
ThreadDemo Waiters[5];
For(int I = 0; I < 5;
I++)
Waiters.[I].Create();
For (int j = 0; j 5; j++)
Auto.Signal();
Manual.Signal();
}
Here a thread object has been
created that waits on the automatic-reset event Auto in its entry routine and
waits on the manual-reset event Manual in its exit routine. After five of these threads are initialized,
five calls to Auto.Signal() release the threads blocked on the automatic-reset
event. One call to the manual-reset
event’s member function Signal()
releases all threads blocked on the manual-reset event.
The PiThreads event synchronization
object is process local and cannot be used to synchronize threads across
multiple processes.