Tekkotsu Homepage
Demos
Overview
Downloads
Dev. Resources
Reference
Credits

Thread Class Reference

Provides a nice wrapping of pthreads library. More...

#include <Thread.h>

Inheritance diagram for Thread:

Detailed Description

Provides a nice wrapping of pthreads library.

If you need to provide cleanup functions on stop(), cancelled(), etc., you should override the destructor to stop and join so that you can be assured that your cleanup will be called if the thread is auto-destructed by going out of scope

Definition at line 38 of file Thread.h.

List of all members.

Classes

struct  cancellation_exception
 this is thrown by testCancel() on systems where pthread_testcancel() doesn't do what we want More...
class  Condition
 Provides an inter-thread signaling and synchronization mechanism. More...
class  Lock
 an inter-thread lock -- doesn't work across processes, only threads within a process. (see MutexLock for inter-process locks) More...
struct  NoCancelScope

Public Member Functions

 Thread ()
 constructor, does not start thread by itself (although subclasses may)
virtual ~Thread ()=0
 destructor, will stop and join the thread, but you should override it to do the same if you provide any cleanup functions
virtual void start ()
 requests that the thread be started, if not already running (you need to create separate instances if you want to run multiple copies)
virtual Threadinterrupt ()
 sends a signal (SIGALRM) to the thread which will interrupt any sleep/read/etc. calls (and trigger interrupted() to be called within the thread)
virtual Threadstop ()
 requests that the thread be stopped gracefully, if running.
virtual Threadkill ()
 sends a SIGUSR1 to the thread, breaking its execution, but still allowing handle_exit (and thus cancelled()) to be called.
virtual Threadmurder ()
 detaches thread and sends SIGSTOP, which immediately halts the thread without any chance for cleanup
virtual void sendSignal (int sig)
 sends a signal to the thread
virtual void * join () const
 blocks calling thread until this Thread has terminated, either via run() returning of its own accord, or a stop() cancelling the thread
virtual void * getReturnValue ()
 returns returnValue, for use with threads which may have intermediate results, or partial results following a cancellation
virtual bool isStarted () const
 indicates whether start() has been called (but may be some delay before isRunning() is true...)
virtual bool isRunning () const
 indicates whether the thread is currently alive and running, implies isStarted()
LockgetStartLock ()
 Acquiring this lock allows you to atomically test whether the thread is already running and (re)start it or stop/join it.
void * getGroup () const
 returns group
void setGroup (void *g)
 assigns group, which will then be inherited by any threads instantiated by this one (the constructor call queries the current thread, no the start() or launch())

Static Public Member Functions

static ThreadgetCurrent ()
 returns the Thread object for the current thread (or NULL for the main thread)
static void initMainThread ()
 should be called before any threads are created to allow some global thread-specific data to be set up
static void releaseMainThread ()
 should be called if you no longer expect to have any threads in use
static void pushNoCancel ()
 should be called whenever a critical section has been entered (i.e. mutex obtained) -- prevents cancel from occurring until popNoCancel() is called
static void popNoCancel (bool doTestCancel=true)
 should be called whenever a critical section is left (i.e. mutex released) -- if it was the last one, tests cancellability as well if doTestCancel (generally should, except in destructors, may already be unwinding from exception, would cause terminate)
static void requestInterruptOnCancel ()
 Should be called before system calls which are not cancellation points, but support interruption by signal.
static void unrequestInterruptOnCancel ()
 Should be called after system calls which are not cancellation points, but support interruption by signal.
static void testCurrentCancel ()
 checks to see if stop() has been called for the current thread, and if so, will exit (passing through handle_exit() first)

Static Public Attributes

static void * CANCELLED = PTHREAD_CANCELED
 return value from join() when the thread was cancelled instead of returning a value

Protected Member Functions

virtual bool launched ()
 called by launch() when thread is first entered, return false to cancel launch (set returnValue as well if you care)
virtual void * run ()
 called by launch() once the thread has been set up; when this returns, the thread ends, see runloop()
virtual unsigned int runloop ()
 override this as a convenient way to define your thread -- return the number of *micro*seconds to sleep before the next call; return -1U to indicate end of processing
virtual void cancelled ()
 called when handle_exit() is triggered, either by the thread being cancelled, or when run() has returned voluntarily
virtual void dereference ()
 called as last instruction of handle_exit(), following cancelled() and all other cleanup. A self-deleting thread should do so here.
virtual void interrupted ()
 called by handleInterrupt() in target thread following call to interrupt(), assuming thread has not been cancelled (which can intercept the interrupt)

Static Protected Member Functions

static void testCancel ()
 checks to see if stop() has been called for the currently executing thread, and if so, will exit (passing through handle_exit() first)
static void * launch (void *msg)
 thread entry point -- calls launched() on the thread (as indicated by msg), and then run()
static void handle_launch_signal (int sig)
 indicates kill() has been called (or SIGUSR1 was sent from some other source) while launch() was still running
static void handle_signal (int sig)
 indicates kill() has been called (or SIGUSR1 was sent from some other source)
static void handle_exit (void *th)
 indicates the thread is exiting, either voluntary (run() returned), stop(), or kill() -- calls cancelled() for the thread as indicated by th
static void handleInterrupt (int signal)
 called by SIGALRM signal handler installed by interrupt() just before it posts the corresponding SIGALRM
static void warnSelfUndestructed (void *msg)
 emit a warning that the last thread exited while the self-pointer thread-specific key still exists (need to call releaseMainThread() or handle_exit())

Protected Attributes

struct Threadstorage_t * pt
 stores the actual pthread data fields
bool started
 set to true once start() has been called, set back to false by handle_exit(), or by murder() itself
bool running
 set to true once launch() has been called, set back to false by handle_exit(), or by murder() itself
bool exited
 set to true once handle_exit() or murder() has been called, set back to false by start() (and initially by constructor)
void * returnValue
 indicates the value to be returned by the thread entry point (and thus passed back to join()) -- set this in runloop() or launched(), overridden by run()'s return value
unsigned int noCancelDepth
 depth of the pushNoCancel() stack
unsigned int reqIntrDepth
 depth of the requestInterruptOnCancel() stack
int cancelOrig
 cancel status at root of no-cancel stack (may be no-cancel through and through)
bool cancelRequested
 set to true if using signal-based thread cancellation instead of pthread_cancel
bool cancelInProgress
 set to true if the cancellation has been triggered and stack unwind is in progress (don't throw anything!)
void * group
 indicates a common group of threads, inherited from the thread which created this one, default NULL if created from main thread
stacktrace::StackFramestartTrace
 stores a stack trace of the call to start(), for error reporting and debugging
Lock startLock
 prevents concurrent starts
Lock stopLock
 prevents concurrent stops

Private Member Functions

 Thread (const Thread &r)
 don't call, not a well defined operation
Threadoperator= (const Thread &r)
 don't call, not a well defined operation

Constructor & Destructor Documentation

Thread::Thread (  ) 

constructor, does not start thread by itself (although subclasses may)

Definition at line 46 of file Thread.cc.

Thread::~Thread (  )  [pure virtual]

destructor, will stop and join the thread, but you should override it to do the same if you provide any cleanup functions

Note that this destructor will send a stop() signal... if you want your subclass to let the thread run to its "natural" completion on destruction, you can either pushNoCancel() within the thread, or override the destructor to join() without stop()

Definition at line 60 of file Thread.cc.

Thread::Thread ( const Thread r  )  [private]

don't call, not a well defined operation


Member Function Documentation

virtual void Thread::cancelled (  )  [protected, virtual]

called when handle_exit() is triggered, either by the thread being cancelled, or when run() has returned voluntarily

Reimplemented in MessageQueueStatusThread.

Definition at line 216 of file Thread.h.

Referenced by handle_exit(), and warnSelfUndestructed().

virtual void Thread::dereference (  )  [protected, virtual]

called as last instruction of handle_exit(), following cancelled() and all other cleanup. A self-deleting thread should do so here.

Definition at line 218 of file Thread.h.

Referenced by handle_exit(), and stop().

Thread * Thread::getCurrent (  )  [static]

returns the Thread object for the current thread (or NULL for the main thread)

Definition at line 238 of file Thread.cc.

Referenced by handle_exit(), handleInterrupt(), popNoCancel(), pushNoCancel(), requestInterruptOnCancel(), testCurrentCancel(), Thread(), unrequestInterruptOnCancel(), warnSelfUndestructed(), and ~Thread().

void* Thread::getGroup (  )  const

returns group

Definition at line 198 of file Thread.h.

Referenced by Thread().

virtual void* Thread::getReturnValue (  )  [virtual]

returns returnValue, for use with threads which may have intermediate results, or partial results following a cancellation

Definition at line 162 of file Thread.h.

Lock& Thread::getStartLock (  ) 

Acquiring this lock allows you to atomically test whether the thread is already running and (re)start it or stop/join it.

Definition at line 195 of file Thread.h.

void Thread::handle_exit ( void *  th  )  [static, protected]

indicates the thread is exiting, either voluntary (run() returned), stop(), or kill() -- calls cancelled() for the thread as indicated by th

Definition at line 370 of file Thread.cc.

Referenced by handle_launch_signal(), and launch().

void Thread::handle_launch_signal ( int  sig  )  [static, protected]

indicates kill() has been called (or SIGUSR1 was sent from some other source) while launch() was still running

Definition at line 361 of file Thread.cc.

Referenced by launch().

void Thread::handle_signal ( int  sig  )  [static, protected]

indicates kill() has been called (or SIGUSR1 was sent from some other source)

Definition at line 366 of file Thread.cc.

Referenced by launch().

void Thread::handleInterrupt ( int  signal  )  [static, protected]

called by SIGALRM signal handler installed by interrupt() just before it posts the corresponding SIGALRM

tests for thread cancel condition before calling on to interrupted()

Reimplemented in PollThread.

Definition at line 481 of file Thread.cc.

Referenced by interrupt().

void Thread::initMainThread (  )  [static]

should be called before any threads are created to allow some global thread-specific data to be set up

Definition at line 251 of file Thread.cc.

Thread & Thread::interrupt (  )  [virtual]

sends a signal (SIGALRM) to the thread which will interrupt any sleep/read/etc. calls (and trigger interrupted() to be called within the thread)

This may be called to request a cancellation on systems which don't directly support pthread_cancel they way we would like. See stop().

Definition at line 135 of file Thread.cc.

Referenced by CallbackPollThread::resetPeriod(), and stop().

virtual void Thread::interrupted (  )  [protected, virtual]

called by handleInterrupt() in target thread following call to interrupt(), assuming thread has not been cancelled (which can intercept the interrupt)

Reimplemented in PollThread.

Definition at line 232 of file Thread.h.

Referenced by handleInterrupt().

virtual bool Thread::isRunning (  )  const [virtual]

indicates whether the thread is currently alive and running, implies isStarted()

Definition at line 168 of file Thread.h.

Referenced by interrupt(), CallbackPollThread::resetPeriod(), and sendSignal().

virtual bool Thread::isStarted (  )  const [virtual]
void * Thread::join (  )  const [virtual]

blocks calling thread until this Thread has terminated, either via run() returning of its own accord, or a stop() cancelling the thread

return value is the response from run(), or CANCELLED if stop() was called. See getReturnValue() as a possible way to get results from a cancelled thread.

Definition at line 221 of file Thread.cc.

Referenced by MessageReceiver::finish(), ThreadedMessageQueue< EventBase * >::finishCallback(), ThreadedMessageQueue< EventBase * >::finishQueue(), FailsafeThread::runloop(), ThreadedMessageQueue< EventBase * >::stopCallback(), MessageReceiver::~MessageReceiver(), PollThread::~PollThread(), and ~Thread().

Thread & Thread::kill (  )  [virtual]

sends a SIGUSR1 to the thread, breaking its execution, but still allowing handle_exit (and thus cancelled()) to be called.

Beware if your thread uses mutual exclusion locks, this can cause the thread to terminate while still holding locks Returns *this, for convenience of chaining a call to join()

Definition at line 190 of file Thread.cc.

void * Thread::launch ( void *  msg  )  [static, protected]

thread entry point -- calls launched() on the thread (as indicated by msg), and then run()

Definition at line 297 of file Thread.cc.

Referenced by start().

virtual bool Thread::launched (  )  [protected, virtual]

called by launch() when thread is first entered, return false to cancel launch (set returnValue as well if you care)

Reimplemented in MessageQueueStatusThread, and MessageReceiver.

Definition at line 207 of file Thread.h.

Referenced by launch().

Thread & Thread::murder (  )  [virtual]

detaches thread and sends SIGSTOP, which immediately halts the thread without any chance for cleanup

Beware if your thread uses mutual exclusion locks, this will cause the thread to terminate while still holding locks. Returns *this, for convenience of chaining a call to join()

Definition at line 195 of file Thread.cc.

Thread& Thread::operator= ( const Thread r  )  [private]

don't call, not a well defined operation

void Thread::popNoCancel ( bool  doTestCancel = true  )  [static]

should be called whenever a critical section is left (i.e. mutex released) -- if it was the last one, tests cancellability as well if doTestCancel (generally should, except in destructors, may already be unwinding from exception, would cause terminate)

Definition at line 420 of file Thread.cc.

Referenced by MessageReceiver::runloop(), Thread::Lock::trylock(), Thread::Lock::unlock(), unrequestInterruptOnCancel(), and Thread::NoCancelScope::~NoCancelScope().

void Thread::pushNoCancel (  )  [static]

should be called whenever a critical section has been entered (i.e. mutex obtained) -- prevents cancel from occurring until popNoCancel() is called

Definition at line 400 of file Thread.cc.

Referenced by Thread::Lock::lock(), Thread::NoCancelScope::NoCancelScope(), requestInterruptOnCancel(), MessageReceiver::runloop(), and Thread::Lock::trylock().

void Thread::releaseMainThread (  )  [static]

should be called if you no longer expect to have any threads in use

Definition at line 258 of file Thread.cc.

void Thread::requestInterruptOnCancel (  )  [static]

Should be called before system calls which are not cancellation points, but support interruption by signal.

On OS X, everything is done this way, so no need to call this function. Only needed for calls on systems where we actually use pthread_cancel (Linux), but at system calls which are not cancellation points. At the moment, semop() is the only known case.

Definition at line 447 of file Thread.cc.

Referenced by SemaphoreManager::add_testZero(), SemaphoreManager::add_testZero_add(), SemaphoreManager::lower(), SemaphoreManager::testZero(), and SemaphoreManager::testZero_add().

void * Thread::run (  )  [protected, virtual]

called by launch() once the thread has been set up; when this returns, the thread ends, see runloop()

Default implementation repeatedly calls runloop(), usleep(), and testCancel(). If you override, you should also be sure to call testCancel occasionally in order to support stop() If function returns a value, that value overrides returnValue. If cancel occurs, returnValue is used.

Reimplemented in CallbackThread, MessageQueueStatusThread, PollThread, and ThreadedMessageQueue< T >::ReceiverThread< F, C >.

Definition at line 122 of file Thread.cc.

Referenced by launch().

virtual unsigned int Thread::runloop (  )  [protected, virtual]

override this as a convenient way to define your thread -- return the number of *micro*seconds to sleep before the next call; return -1U to indicate end of processing

Reimplemented in FailsafeThread, and MessageReceiver.

Definition at line 214 of file Thread.h.

Referenced by PollThread::poll(), and run().

void Thread::sendSignal ( int  sig  )  [virtual]

sends a signal to the thread

Definition at line 207 of file Thread.cc.

Referenced by interrupt(), kill(), and murder().

void Thread::setGroup ( void *  g  ) 

assigns group, which will then be inherited by any threads instantiated by this one (the constructor call queries the current thread, no the start() or launch())

Definition at line 200 of file Thread.h.

void Thread::start (  )  [virtual]

requests that the thread be started, if not already running (you need to create separate instances if you want to run multiple copies)

Reimplemented in PollThread.

Definition at line 84 of file Thread.cc.

Referenced by MessageQueueStatusThread::addStatusListener(), CallbackThread::CallbackThread(), FailsafeThread::FailsafeThread(), MessageReceiver::MessageReceiver(), FailsafeThread::runloop(), MessageQueueStatusThread::setMessageQueue(), ThreadedMessageQueue< EventBase * >::spawnCallback(), and CallbackThread::~CallbackThread().

Thread & Thread::stop (  )  [virtual]

requests that the thread be stopped gracefully, if running.

A cancel flag is sent, and the thread will be stopped at next cancel point, defined by whenever testCancel(), or a set of other system functions, are called. See your system's pthread_testcancel() manual page for a list of cancel points.

This function may imply a call to interrupt() on systems which have extremely limited system cancel points or don't handle thread cancellation as a C++ exception (currently this consists of Mac OS X and possibly other BSD-based systems).

This means that you should be able to rely on using try/catch(...) to handle both exceptions as well as thread cancellation, but interruptable system calls should test errno for EINTR and call testCancel() when it is encountered to ensure portability.

Returns *this, for convenience of chaining a call to join()

See also:
pushNoCancel(), popNoCancel()

Reimplemented in MessageQueueStatusThread, and MessageReceiver.

Definition at line 149 of file Thread.cc.

Referenced by ThreadedMessageQueue< EventBase * >::finishCallback(), ThreadedMessageQueue< EventBase * >::finishQueue(), ThreadedMessageQueue< EventBase * >::stopCallback(), PollThread::~PollThread(), and ~Thread().

static void Thread::testCancel (  )  [static, protected]

checks to see if stop() has been called for the currently executing thread, and if so, will exit (passing through handle_exit() first)

Definition at line 221 of file Thread.h.

Referenced by handleInterrupt(), launch(), popNoCancel(), run(), PollThread::run(), MessageQueueStatusThread::run(), FailsafeThread::runloop(), and unrequestInterruptOnCancel().

void Thread::testCurrentCancel (  )  [static]

checks to see if stop() has been called for the current thread, and if so, will exit (passing through handle_exit() first)

Definition at line 266 of file Thread.cc.

Referenced by testCancel(), Thread::Condition::timedwait(), and Thread::Condition::wait().

void Thread::unrequestInterruptOnCancel (  )  [static]

Should be called after system calls which are not cancellation points, but support interruption by signal.

On OS X, everything is done this way, so no need to call this function. Only needed for calls on systems where we actually use pthread_cancel (Linux), but at system calls which are not cancellation points. At the moment, semop() is the only known case.

Definition at line 461 of file Thread.cc.

Referenced by SemaphoreManager::add_testZero(), SemaphoreManager::add_testZero_add(), SemaphoreManager::lower(), SemaphoreManager::testZero(), and SemaphoreManager::testZero_add().

void Thread::warnSelfUndestructed ( void *  msg  )  [static, protected]

emit a warning that the last thread exited while the self-pointer thread-specific key still exists (need to call releaseMainThread() or handle_exit())

Definition at line 498 of file Thread.cc.

Referenced by initMainThread().


Member Data Documentation

bool Thread::cancelInProgress [protected]

set to true if the cancellation has been triggered and stack unwind is in progress (don't throw anything!)

Definition at line 262 of file Thread.h.

Referenced by launch(), and testCurrentCancel().

void * Thread::CANCELLED = PTHREAD_CANCELED [static]

return value from join() when the thread was cancelled instead of returning a value

Definition at line 106 of file Thread.h.

Referenced by join(), and launch().

int Thread::cancelOrig [protected]

cancel status at root of no-cancel stack (may be no-cancel through and through)

Definition at line 258 of file Thread.h.

Referenced by launch(), popNoCancel(), and pushNoCancel().

bool Thread::cancelRequested [protected]

set to true if using signal-based thread cancellation instead of pthread_cancel

Definition at line 260 of file Thread.h.

Referenced by join(), start(), stop(), and testCurrentCancel().

bool Thread::exited [protected]

set to true once handle_exit() or murder() has been called, set back to false by start() (and initially by constructor)

Definition at line 248 of file Thread.h.

Referenced by handle_exit(), murder(), start(), and stop().

void* Thread::group [protected]

indicates a common group of threads, inherited from the thread which created this one, default NULL if created from main thread

Definition at line 265 of file Thread.h.

Referenced by getGroup(), setGroup(), and Thread().

struct Threadstorage_t* Thread::pt [protected]

stores the actual pthread data fields

Definition at line 242 of file Thread.h.

Referenced by join(), murder(), sendSignal(), start(), stop(), and ~Thread().

unsigned int Thread::reqIntrDepth [protected]

depth of the requestInterruptOnCancel() stack

Definition at line 255 of file Thread.h.

Referenced by requestInterruptOnCancel(), stop(), and unrequestInterruptOnCancel().

void* Thread::returnValue [protected]

indicates the value to be returned by the thread entry point (and thus passed back to join()) -- set this in runloop() or launched(), overridden by run()'s return value

Definition at line 250 of file Thread.h.

Referenced by getReturnValue(), join(), launch(), run(), and PollThread::run().

bool Thread::running [protected]

set to true once launch() has been called, set back to false by handle_exit(), or by murder() itself

Definition at line 246 of file Thread.h.

Referenced by handle_exit(), isRunning(), launch(), murder(), sendSignal(), MessageQueueStatusThread::setMessageQueue(), stop(), and warnSelfUndestructed().

bool Thread::started [protected]

set to true once start() has been called, set back to false by handle_exit(), or by murder() itself

Definition at line 244 of file Thread.h.

Referenced by handle_exit(), isStarted(), join(), murder(), sendSignal(), start(), stop(), warnSelfUndestructed(), and ~Thread().

Lock Thread::startLock [mutable, protected]

prevents concurrent starts

Definition at line 270 of file Thread.h.

Referenced by getStartLock(), join(), start(), and ~Thread().

stores a stack trace of the call to start(), for error reporting and debugging

Definition at line 268 of file Thread.h.

Referenced by start(), testCurrentCancel(), and ~Thread().

Lock Thread::stopLock [mutable, protected]

prevents concurrent stops

Definition at line 272 of file Thread.h.

Referenced by handle_exit(), and stop().


The documentation for this class was generated from the following files:

Tekkotsu v5.1CVS
Generated Mon May 9 04:59:17 2016 by Doxygen 1.6.3