Google

Main Page   Class Hierarchy   Alphabetical List   Compound List   File List   Compound Members   File Members  

Thread Class Reference

Every thread of execution in an application is created by deriving a unique class from the Thread class and by implementing the Run method. base class used to derive all threads of execution. More...

#include <thread.h>

Inheritance diagram for Thread:

FIFOSession SerialService SocketService TCPSession TTYSession List of all members.

Public Methods

 Thread (bool flag)
 This is actually a special constructor that is used to create a thread "object" for the current execution context when that context is not created via an instance of a derived Thread object itself. More...

 Thread (Semaphore *start = NULL, int pri = 0, size_t stack = 0)
 When a thread object is contructed, a new thread of execution context is created. More...

 Thread (const Thread &th)
 A thread of execution can also be specified by cloning an existing thread. More...

virtual ~Thread ()
 The thread destructor should clear up any resources that have been allocated by the thread. More...

int Start (Semaphore *start = NULL)
 When a new thread is created, it does not begin immediate execution. More...

Thread* getParent (void)
 Gets the pointer to the Thread class which created the current thread object. More...

void SignalThread (int signo)
 Delivers a Posix signal to the current thread. More...

void Suspend (void)
 Suspends execution of the selected thread. More...

void Suspend (void)
 Suspends execution of the selected thread. More...

void Resume (void)
 Resumes execution of the selected thread.

void Resume (void)
 Resumes execution of the selected thread.

int getCancel (void)
 Used to retrieve the cancellation mode in effect for the selected thread. More...

bool isRunning (void)
 Verifies if the thread is still running or has already been terminated but not yet deleted. More...

bool isThread (void)
 Tests to see if the current execution context is the same as the specified thread object. More...


Protected Methods

virtual void Run (void) = 0
 All threads execute by deriving the Run method of Thread. More...

virtual void First (void)
 This method is called for the very first instance of a new thread being created in a multi-threaded application. More...

virtual void Final (void)
 A thread that is self terminating, either by invoking Exit() or leaving it's Run(), will have this method called. More...

virtual void Initial (void)
 The initial method is called by a newly created thread when it starts execution. More...

virtual void* getExtended (void)
 Since getParent() and getThread only refer to an object of the Thread "base" type, this virtual method can be replaced in a derived class with something that returns data specific to the derived class that can still be accessed through the pointer returned by getParent() and getThread. More...

virtual void Notify (Thread *th)
 When a thread terminates, it now sends a notification message to the parent thread which created it. More...

void SignalParent (signo_t signo)
 In the Posix version of Common C++, this can be used to send a signal into the parent thread of the current object. More...

void SignalMain (signo_t signo)
 In the Posix version of Common C++, this can be used to send a signal into the nain application thread. More...

virtual void OnTimer (void)
 A derivable method to call when a SIGALRM is being delivered to a specific thread.

virtual void OnHangup (void)
 A derived method to handle hangup events being delivered to a specific thread.

virtual void OnException (void)
 A derived method to call when a SIGABRT is being delivered to a specific thread.

virtual void OnDisconnect (void)
 A derived method to call when a SIGPIPE is being delivered to a specific thread.

virtual void OnPolling (void)
 A derived method to handle asynchronous I/O requests delivered to the specified thread.

virtual void OnSignal (int signo)
 A derivable method to call for delivering a signal event to a specified thread. More...

void Sleep (timeout_t msec)
 A thread-safe sleep call. More...

void Exit (void)
 Used to properly exit from a Thread derived Run() or Initial() method. More...

void setTimer (timeout_t timer)
 Used to specify a timeout event that can be delivered to the current thread via SIGALRM. More...

timeout_t getTimer (void)
 Gets the time remaining for the current threads timer before it expires. More...

void endTimer (void)
 Terminates the timer before the timeout period has expired. More...

void WaitSignal (signo_t signo)
 Used to wait on a Posix signal from another thread. More...

void Yield (void)
 Yeilds the current thread's CPU time slice to allow another thread to begin immediate execution.

void testCancel (void)
 test a cancellation point for deferred thread cancellation.

void setCancel (thread_cancel_t mode)
 Sets thread cancellation mode. More...

void setSuspend (thread_suspend_t mode)
 Sets the thread's ability to be suspended from execution. More...

void setSignal (int signo, bool mode)
 Used to enable or disable a signal within the current thread. More...

void Terminate (void)
 Used by another thread to terminate the current thread. More...

void clrParent (void)
 clear parent thread relationship.


Friends

class  Slog
void execHandler (Thread *th)
void sigHandler (int signo)
Thread* getThread (void)
throw_t getException (void)
 Get exception mode of the current thread. More...

void setException (throw_t mode)
 Set exception mode of the current thread. More...

void ccxx_sleep (timeout_t msec)
 Thread safe sleep call replacement. More...

void suspend (Thread &th)
 Suspend the execution of the specified thread. More...

void resume (Thread &th)
 Resume execution of the specified thread. More...

void operator++ (Thread &th)
 Signal the semaphore that the specified thread is waiting for before beginning execution. More...

void operator-- (Thread &th)
int start (Thread &th, Semaphore *start)
 Start execution of a specified thread.

void siginstall (int signo)
 Install a signal handler for use by threads and the OnSignal() event notification handler. More...


Detailed Description

Every thread of execution in an application is created by deriving a unique class from the Thread class and by implementing the Run method. base class used to derive all threads of execution.

The base Thread class supports encapsulation of the generic threading methods implemented on various target operating systems. This includes the ability to start and stop threads in a synchronized and controllable manner, the ability to specify thread execution priority, and thread specific "system call" wrappers, such as for sleep and yield. A thread exception is thrown if the thread cannot be created. Threading was the first part of Common C++ I wrote, back when it was still the APE library. My goal for Common C++ threading has been to make threading as natural and easy to use in C++ application development as threading is in Java. With this said, one does not need to use threading at all to take advantage of Common C++. However, all Common C++ classes are designed at least to be thread-aware/thread-safe as appropriate and necessary.

Common C++ threading is currently built either from the Posix "pthread" library or using the win32 SDK. In that the Posix "pthread" draft has gone through many revisions, and many system implementations are only marginally compliant, and even then usually in different ways, I wrote a large series of autoconf macros found in ost_pthread.m4 which handle the task of identifying which pthread features and capabilities your target platform supports. In the process I learned much about what autoconf can and cannot do for you..

Currently the GNU Portable Thread library (GNU pth) is not directly supported in Common C++. While GNU "Pth" doesn't offer direct native threading support or benefit from SMP hardware, many of the design advantages of threading can be gained from it's use, and the Pth pthread "emulation" library should be usable with Common C++. In the future, Common C++ will directly support Pth, as well as OS/2 and BeOS native threading API's.

Common C++ itself defines a fairly "neutral" threading model that is not tied to any specific API such as pthread, win32, etc. This neutral thread model is contained in a series of classes which handle threading and synchronization and which may be used together to build reliable threaded applications.

Common C++ defines application specific threads as objects which are derived from the Common C++ "Thread" base class. At minimum the "Run" method must be implemented, and this method essentially is the "thread", for it is executed within the execution context of the thread, and when the Run method terminates the thread is assumed to have terminated.

Common C++ allows one to specify the running priority of a newly created thread relative to the "parent" thread which is the thread that is executing when the constructor is called. Since most newer C++ implementations do not allow one to call virtual constructors or virtual methods from constructors, the thread must be "started" after the constructor returns. This is done either by defining a "starting" semaphore object that one or more newly created thread objects can wait upon, or by invoking an explicit "Start" member function.

Threads can be "suspended" and "resumed". As this behavior is not defined in the Posix "pthread" specification, it is often emulated through signals. Typically SIGUSR1 will be used for this purpose in Common C++ applications, depending in the target platform. On Linux, since threads are indeed processes, SIGSTP and SIGCONT can be used. On solaris, the Solaris thread library supports suspend and resume directly.

Threads can be canceled. Not all platforms support the concept of externally cancelable threads. On those platforms and API implementations that do not, threads are typically canceled through the action of a signal handler.

As noted earlier, threads are considered running until the "Run" method returns, or until a cancellation request is made. Common C++ threads can control how they respond to cancellation, using setCancellation(). Cancellation requests can be ignored, set to occur only when a cancellation "point" has been reached in the code, or occur immediately. Threads can also exit by returning from Run() or by invoking the Exit() method.

Generally it is a good practice to initialize any resources the thread may require within the constructor of your derived thread class, and to purge or restore any allocated resources in the destructor. In most cases, the destructor will be executed after the thread has terminated, and hence will execute within the context of the thread that requested a join rather than in the context of the thread that is being terminated. Most destructors in derived thread classes should first call Terminate() to make sure the thread has stopped running before releasing resources.

A Common C++ thread is normally canceled by deleting the thread object. The process of deletion invokes the thread's destructor, and the destructor will then perform a "join" against the thread using the Terminate() function. This behavior is not always desirable since the thread may block itself from cancellation and block the current "delete" operation from completing. One can alternately invoke Terminate() directly before deleting a thread object.

When a given Common C++ thread exits on it's own through it's Run() method, a "Final" method will be called. This Final method will be called while the thread is "detached". If a thread object is constructed through a "new" operator, it's final method can be used to "self delete" when done, and allows an independent thread to construct and remove itself autonomously.

A special global function, getThread, is provided to identify the thread object that represents the current execution context you are running under. This is sometimes needed to deliver signals to the correct thread. Since all thread manipulation should be done through the Common C++ (base) thread class itself, this provides the same functionality as things like "pthread_self" for Common C++.

Common C++ threads are often aggregated into other classes to provide services that are "managed" from or operate within the context of a thread, even within the Common C++ framework itself. A good example of this is the TCPSession class, which essentially is a combination of a TCP client connection and a separate thread the user can define by deriving a class with a Run() method to handle the connected service. This aggregation logically connects the successful allocation of a given resource with the construction of a thread to manage and perform operations for said resource.

Threads are also used in "service pools". In Common C++, a service pool is one or more threads that are used to manage a set of resources. While Common C++ does not provide a direct "pool" class, it does provide a model for their implementation, usually by constructing an array of thread "service" objects, each of which can then be assigned the next new instance of a given resource in turn or algorithmically.

Threads have signal handlers associated with them. Several signal types are "predefined" and have special meaning. All signal handlers are defined as virtual member functions of the Thread class which are called when a specific signal is received for a given thread. The "SIGPIPE" event is defined as a "Disconnect" event since it's normally associated with a socket disconnecting or broken fifo. The Hangup() method is associated with the SIGHUP signal. All other signals are handled through the more generic Signal().

Incidently, unlike Posix, the win32 API has no concept of signals, and certainly no means to define or deliver signals on a per-thread basis. For this reason, no signal handling is supported or emulated in the win32 implementation of Common C++ at this time.

In addition to TCPStream, there is a TCPSession class which combines a thread with a TCPStream object. The assumption made by TCPSession is that one will service each TCP connection with a separate thread, and this makes sense for systems where extended connections may be maintained and complex protocols are being used over TCP.

Author(s):
David Sugar <dyfet@ostel.com>


Constructor & Destructor Documentation

Thread::Thread ( bool flag )
 

This is actually a special constructor that is used to create a thread "object" for the current execution context when that context is not created via an instance of a derived Thread object itself.

This constructor does not support First.

Parameters:
bool   used if the main "thread" of the application.

Thread::Thread ( Semaphore * start = NULL,
int pri = 0,
size_t stack = 0 )
 

When a thread object is contructed, a new thread of execution context is created.

This constructor allows basic properties of that context (thread priority, stack space, etc) to be defined. The starting condition is also specified for whether the thread is to wait on a semaphore before begining execution or wait until it's start method is called.

Parameters:
start   semaphore to wait before executing thread.
pri   thread base priority relative to it's parent.
stack   space as needed in some implementations.

Thread::Thread ( const Thread & th )
 

A thread of execution can also be specified by cloning an existing thread.

The existing thread's properties (cancel mode, priority, etc), are also duplicated.

Parameters:
th   currently executing thread object to clone.

Thread::~Thread ( ) [inline, virtual]
 

The thread destructor should clear up any resources that have been allocated by the thread.

The desctructor of a derived thread should begin with Terminate() and is presumed to then execute within the context of the thread causing terminaton.


Member Function Documentation

void Thread::Exit ( void ) [inline, protected]
 

Used to properly exit from a Thread derived Run() or Initial() method.

Terminates execution of the current thread and calls the derived classes Final() method.

void Thread::Final ( void ) [inline, protected, virtual]
 

A thread that is self terminating, either by invoking Exit() or leaving it's Run(), will have this method called.

It can be used to self delete the current object assuming the object was created with new on the heap rather than stack local, hence one may often see Final defined as "delete this" in a derived thread class. A Final method, while running, cannot be terminated or cancelled by another thread.

See also:
Exit , Run

Reimplemented in TCPSession.

void Thread::First ( void ) [inline, protected, virtual]
 

This method is called for the very first instance of a new thread being created in a multi-threaded application.

Hence, it is only called once, and by the derived Thread class that happens to be created first.

void Thread::Initial ( void ) [inline, protected, virtual]
 

The initial method is called by a newly created thread when it starts execution.

This method is ran with deferred cancellation disabled by default. The Initial method is given a seperate handler so that it can create temporary objects on it's own stack frame, rather than having objects created on Run() that are only needed by startup and yet continue to consume stack space.

See also:
Run

Reimplemented in TCPSession.

void Thread::Notify ( Thread * th ) [inline, protected, virtual]
 

When a thread terminates, it now sends a notification message to the parent thread which created it.

The actual use of this notification is left to be defined in a derived class.

Parameters:
th   the thread that has terminated.

void Thread::OnDisconnect ( void ) [inline, protected, virtual]
 

A derived method to call when a SIGPIPE is being delivered to a specific thread.

void Thread::OnException ( void ) [inline, protected, virtual]
 

A derived method to call when a SIGABRT is being delivered to a specific thread.

void Thread::OnHangup ( void ) [inline, protected, virtual]
 

A derived method to handle hangup events being delivered to a specific thread.

void Thread::OnPolling ( void ) [inline, protected, virtual]
 

A derived method to handle asynchronous I/O requests delivered to the specified thread.

void Thread::OnSignal ( int signo ) [inline, protected, virtual]
 

A derivable method to call for delivering a signal event to a specified thread.

Parameters:
signo   posix signal id.

void Thread::OnTimer ( void ) [inline, protected, virtual]
 

A derivable method to call when a SIGALRM is being delivered to a specific thread.

void Thread::Resume ( void ) [inline]
 

Resumes execution of the selected thread.

void Thread::Resume ( void ) [inline]
 

Resumes execution of the selected thread.

void Thread::Run ( void ) [protected, pure virtual]
 

All threads execute by deriving the Run method of Thread.

This method is called after Initial to begin normal operation of the thread. If the method terminates, then the thread will also terminate after notifying it's parent and calling it's Final() method.

See also:
Initial

void Thread::SignalMain ( signo_t signo ) [inline, protected]
 

In the Posix version of Common C++, this can be used to send a signal into the nain application thread.

Parameters:
signo   a posix signal id.

void Thread::SignalParent ( signo_t signo ) [inline, protected]
 

In the Posix version of Common C++, this can be used to send a signal into the parent thread of the current object.

Parameters:
signo   a posix signal id.

void Thread::SignalThread ( int signo ) [inline]
 

Delivers a Posix signal to the current thread.

Parameters:
signo   a posix signal id.

void Thread::Sleep ( timeout_t msec ) [inline, protected]
 

A thread-safe sleep call.

On most Posix systems, "sleep()" is implimented with SIGALRM making it unusable from multipe threads. Pthread libraries often define an alternate "sleep" handler such as usleep(), nanosleep(), or nap(), that is thread safe, and also offers a higher timer resolution.

Parameters:
msec   timeout in milliseconds.

int Thread::Start ( Semaphore * start = NULL )
 

When a new thread is created, it does not begin immediate execution.

This is because the derived class virtual tables are not properly loaded at the time the C++ object is created within the constructor itself, at least in some compiler/system combinations. The thread can either be told to wait for an external semaphore, or it can be started directly after the constructor completes by calling the Start() method.

Returns:
error code if execution fails.
Parameters:
start   optional starting semaphore to alternately use.

void Thread::Suspend ( void ) [inline]
 

Suspends execution of the selected thread.

Pthreads do not normally support suspendable threads, so the behavior is simulated with signals. On systems such as Linux that define threads as processes, SIGSTOP and SIGCONT may be used.

void Thread::Suspend ( void ) [inline]
 

Suspends execution of the selected thread.

Pthreads do not normally support suspendable threads, so the behavior is simulated with signals. On systems such as Linux that define threads as processes, SIGSTOP and SIGCONT may be used.

void Thread::Terminate ( void ) [protected]
 

Used by another thread to terminate the current thread.

Termination actually occurs based on the current setCancel() mode. When the current thread does terminate, control is returned to the requesting thread. Terminate() should always be called at the start of any destructor of a class derived from Thread to assure the remaining part of the destructor is called without the thread still executing.

void Thread::WaitSignal ( signo_t signo ) [protected]
 

Used to wait on a Posix signal from another thread.

This can be used as a crude rondevious/synchronization method between threads.

Parameters:
signo   a posix signal id.

void Thread::Yield ( void ) [protected]
 

Yeilds the current thread's CPU time slice to allow another thread to begin immediate execution.

void Thread::clrParent ( void ) [inline, protected]
 

clear parent thread relationship.

void Thread::endTimer ( void ) [protected]
 

Terminates the timer before the timeout period has expired.

This prevents the timer from sending it's SIGALRM and makes the timer available to other threads.

int Thread::getCancel ( void ) [inline]
 

Used to retrieve the cancellation mode in effect for the selected thread.

Returns:
cancellation mode constant.

void * Thread::getExtended ( void ) [inline, protected, virtual]
 

Since getParent() and getThread only refer to an object of the Thread "base" type, this virtual method can be replaced in a derived class with something that returns data specific to the derived class that can still be accessed through the pointer returned by getParent() and getThread.

Returns:
pointer to derived class specific data.

Thread * Thread::getParent ( void ) [inline]
 

Gets the pointer to the Thread class which created the current thread object.

Returns:
a Thread *, or "(Thread *)this" if no parent.

timeout_t Thread::getTimer ( void ) [protected]
 

Gets the time remaining for the current threads timer before it expires.

Returns:
time remaining before timer expires in milliseconds.

bool Thread::isRunning ( void )
 

Verifies if the thread is still running or has already been terminated but not yet deleted.

Returns:
true if the thread is still executing.

bool Thread::isThread ( void )
 

Tests to see if the current execution context is the same as the specified thread object.

Returns:
true if the current context is this object.

void Thread::setCancel ( thread_cancel_t mode ) [protected]
 

Sets thread cancellation mode.

Threads can either be set immune to termination (THREAD_CANCEL_DISABLED), can be set to terminate when reaching specific "thread cancellation points" (THREAD_CANCEL_DEFERRED) or immediately when Terminate is requested (THREAD_CANCEL_IMMEDIATE).

Parameters:
mode   for cancellation of the current thread.

void Thread::setSignal ( int signo,
bool mode ) [protected]
 

Used to enable or disable a signal within the current thread.

Parameters:
signo   posix signal id.
active   set to true to enable.

void Thread::setSuspend ( thread_suspend_t mode ) [protected]
 

Sets the thread's ability to be suspended from execution.

The thread may either have suspend enabled (THREAD_SUSPEND_ENABLE) or disabled (THREAD_SUSPEND_DISABLE).

Parameters:
mode   for suspend.

void Thread::setTimer ( timeout_t timer ) [protected]
 

Used to specify a timeout event that can be delivered to the current thread via SIGALRM.

When the timer expires, the OnTimer() method is called for the thread. At present, only one thread timer can be active at any given time. On some operating systems (including Linux) a timer can be active on each thread.

Parameters:
timer   timeout in milliseconds.

void Thread::testCancel ( void ) [protected]
 

test a cancellation point for deferred thread cancellation.


Friends And Related Function Documentation

class Slog [friend]
 

void ccxx_sleep ( timeout_t msec ) [friend]
 

Thread safe sleep call replacement.

This is mapped into sleep().

Parameters:
msec   timeout in millisecond time range.

void execHandler ( Thread * th ) [friend]
 

throw_t getException ( void ) [friend]
 

Get exception mode of the current thread.

Returns:
exception mode.

Thread* getThread ( void ) [friend]
 

void operator++ ( Thread & th ) [friend]
 

Signal the semaphore that the specified thread is waiting for before beginning execution.

Parameters:
th   specified thread.

void operator-- ( Thread & th ) [friend]
 

void resume ( Thread & th ) [friend]
 

Resume execution of the specified thread.

Parameters:
th   specified thread.

void setException ( throw_t mode ) [friend]
 

Set exception mode of the current thread.

Returns:
exception mode.

void sigHandler ( int signo ) [friend]
 

void siginstall ( int signo ) [friend]
 

Install a signal handler for use by threads and the OnSignal() event notification handler.

Parameters:
signo   posix signal id.

int start ( Thread & th,
Semaphore * start ) [friend]
 

Start execution of a specified thread.

void suspend ( Thread & th ) [friend]
 

Suspend the execution of the specified thread.

Parameters:
th   specified thread.


The documentation for this class was generated from the following file:
Generated at Fri Mar 23 10:47:56 2001 for CommonC++ by doxygen1.2.1 written by Dimitri van Heesch, © 1997-2000