4. Critical Section Object
The OSI_Threads library provides the
object Crit_Sec, which offers critical section synchronization services across
Win32 or POSIX platforms. The
definition of Crit_Sec is in the file crit_sec.h, which must be included after
the #define WIN or #define POSIX statement and the inclusion of the thread.h
header file. The public elements of the
class crit_sec can be seen below.
class Crit_Sec
{
public:
Crit_Sec();
~Crit_Sec();
void Enter();
void Leave();
};
The member function Enter() is called to enter a
critical section of code. If another
thread has already entered a critical section of code protected by the same
object and not yet called Leave(), subsequent threads which try to call Enter()
will be blocked. In the example below,
a number of threads are created which all access a region of code within their
thread routine that is protected by the same critical section.
#define POSIX or #define WIN
#include<thread.h>
#include<crit_sec.h>
Crit_Sec
CSEC; //The critical section object is
declared as a global variable
class ThreadDemo : public
Thread
{
public:
ThreadDemo() : Thread() {}
void EntryRoutine(void)
{
CSEC.Enter() // Enter
critical section protected region of code
// Manipulate protected data here
CSEC.Leave() // Leave
critical section protected region of code
}
void ExitRoutine(void) {}
};
void main()
{
ThreadDemo Crit_Threads[10]; //Declare threads
for(int x = 0; x < 10; x++)
Crit_Threads[I].Create(); //Initialize threads in running mode
for(int y = 0; y < 10;
y++)
Crit_Threads[y].Join(); //Wait for threads to complete execution
}
The critical section here
synchronizes access to the region of code between the calls to Enter() and the
calls to Leave() that occur in the thread routine. The OSI_Threads critical section object is process local and
cannot be used to implement synchronization across different processes.