nidas  v1.2-1520
Public Types | Public Member Functions | Static Public Member Functions | Protected Member Functions | Private Member Functions | Static Private Member Functions | Private Attributes | Static Private Attributes | List of all members
nidas::util::Thread Class Referenceabstract

#include <Thread.h>

Inheritance diagram for nidas::util::Thread:
Inheritance graph
[legend]

Public Types

enum  runStatus { RUN_CANCELED = -1, RUN_OK = 0, NOT_RUNNING = 1, RUN_EXCEPTION = 2 }
 Values that can be returned by run method. More...
 
enum  SchedPolicy { NU_THREAD_OTHER =SCHED_OTHER, NU_THREAD_FIFO =SCHED_FIFO, NU_THREAD_RR =SCHED_RR }
 

Public Member Functions

 Thread (const std::string &name, bool detached=false)
 Constructor for a thread, giving it a name. More...
 
 Thread (const Thread &x)
 Copy constructor. More...
 
virtual ~Thread ()
 Thread destructor. More...
 
virtual void start () throw (Exception)
 Start the thread running, meaning execute the run method in a separate thread. More...
 
virtual int join () throw (Exception)
 The calling thread joins this thread, waiting until the thread finishes, which means either that the run() method returned, the thread called pthread_exit() or the thread was cancelled. More...
 
virtual void kill (int sig) throw (Exception)
 Send a signal to this thread. More...
 
virtual void cancel () throw (Exception)
 Cancel this thread. More...
 
virtual void interrupt ()
 Interrupt this thread. More...
 
virtual bool isInterrupted () const
 Return true when this thread has been interrupted. More...
 
virtual bool isRunning () const
 Is this thread running? More...
 
virtual bool isJoined () const
 Has this thread been joined? More...
 
virtual bool isDetached () const
 Is this a detached thread. More...
 
bool isCancelEnabled () const
 Return true if the cancel state of this thread is PTHREAD_CANCEL_ENABLE. More...
 
bool isCancelDeferred () const
 Return true if the cancel type of this thread is PTHREAD_CANCEL_DEFERRED. More...
 
const std::string & getName () const throw ()
 Return the name of this thread. More...
 
const std::string & getFullName () throw ()
 Return a name with a bunch of descriptive fields, specifying whether it is detached, the real-time priority, etc. More...
 
bool setRealTimeRoundRobinPriority (int val) throw (Exception)
 
bool setRealTimeFIFOPriority (int val) throw (Exception)
 
bool setNonRealTimePriority () throw (Exception)
 
void setThreadScheduler (enum SchedPolicy policy, int priority) throw (Exception)
 
void blockSignal (int)
 Block a signal in this thread. More...
 
void unblockSignal (int)
 Install a signal handler and unblock the signal. More...
 
virtual int run ()=0 throw (Exception)
 The method which will run in its own thread. More...
 

Static Public Member Functions

static ThreadcurrentThread ()
 Return the thread object for the current thread. More...
 
static pthread_t currentThreadId ()
 
static ThreadlookupThread (pthread_t id)
 
static const std::string & currentName ()
 Convenience routine to return the name for the current thread, or a string indicating that the name of the thread is unknown. More...
 
static std::string getPolicyString (int policy)
 Convenience function to return a string for the given scheduler policy: "Non-RT", "RT:FIFO", "RT:RR" or "RT:Unknown". More...
 
static int test (int argc, char **argv)
 a test method. More...
 

Protected Member Functions

void setCancelEnabled (bool val)
 Set the cancel state for this thread - false means cancel requests are ignored. More...
 
void setCancelDeferred (bool val)
 Set the cancel type for this thread. More...
 
pthread_t getId () const
 
void testCancel () const
 Check if we have been cancelled. More...
 
virtual bool amInterrupted () const
 Call testCancel, and return true when this thread has been interrupted. More...
 

Private Member Functions

virtual void signalHandler (int, siginfo_t *)
 Signal handler function for this thread. More...
 
virtual int pRun ()
 
void setThreadSchedulerNolock (enum SchedPolicy policy, int priority) throw (Exception)
 
void makeFullName ()
 
void registerThread ()
 Register this current thread with a static registry of threads by id. More...
 
void unregisterThread ()
 
void unsetId ()
 
Threadoperator= (const Thread &x)
 Assignment operator not supported. More...
 

Static Private Member Functions

static void * thr_run (void *me)
 
static void * thr_run_detached (void *me)
 
static void thr_cleanup (void *me)
 
static void thr_cleanup_delete (void *me)
 
static void thr_add_sig (int sig)
 
static void sigAction (int sig, siginfo_t *si, void *vptr)
 

Private Attributes

Mutex _mutex
 Mutex for accessing _id. More...
 
std::string _name
 
std::string _fullname
 
pthread_t _id
 
bool _running
 
bool _interrupted
 
bool _cancel_enabled
 
bool _cancel_deferred
 
pthread_attr_t _thread_attr
 
Exception_exception
 Exception thrown by run method. More...
 
bool _detached
 
sigset_t _blockedSignals
 
sigset_t _unblockedSignals
 

Static Private Attributes

static std::string unknownName = std::string("unknown")
 

Member Enumeration Documentation

Values that can be returned by run method.

User can define other values greater than RUN_EXCEPTION. These values are then returned by int join(). Note that PTHREAD_CANCELLED is -1

Enumerator
RUN_CANCELED 
RUN_OK 
NOT_RUNNING 
RUN_EXCEPTION 
Enumerator
NU_THREAD_OTHER 
NU_THREAD_FIFO 
NU_THREAD_RR 

Constructor & Destructor Documentation

Thread::Thread ( const std::string &  name,
bool  detached = false 
)

Constructor for a thread, giving it a name.

This does not start a processor thread. Use the Thread::start() method to start the processor thread. By default, SIGINT, SIGTERM and SIGHUP signals will be blocked when the thread starts. Use unblockSignal(sig) to unblock them if desired.

References _blockedSignals, _detached, _thread_attr, and _unblockedSignals.

Referenced by test().

Thread::Thread ( const Thread x)

Copy constructor.

Does not create a separate processor thread if the original thread is running.

References _detached, and _thread_attr.

Thread::~Thread ( )
virtual

Thread destructor.

The destructor does not join or cancel a thread.

Users should not invoke the destructor of a detached thread after it has been started. Detached threads call their own destructor when finished.

The following comments pertain to non-deattached threads.

A thread shouldn't be running at the time of destruction.

Non-detached threads also should have been joined before the destructor is called.

This destructor will complain to cerr if either of the two above situations exists. These situations are errors on the part of the user of Thread and should be corrected.

References _detached, _exception, _thread_attr, getName(), isJoined(), isRunning(), PLOG, and nidas::util::Exception::what().

Member Function Documentation

bool Runnable::amInterrupted ( ) const
protectedvirtualinherited

Call testCancel, and return true when this thread has been interrupted.

This is protected because it should only called within the run method of the thread.

Referenced by nidas::core::SampleOutputRequestThread::run(), nidas::core::Looper::run(), nidas::dynld::isff::GOESOutput::run(), nidas::core::DSMServerStat::run(), and test().

void Thread::blockSignal ( int  sig)

Block a signal in this thread.

This method is usually called before this Thread has started. If this Thread is currently running, then this method is only effective if called from this Thread, i.e. from its own run() method.

Because SIGINT, SIGTERM and SIGHUP are typically caught in the main thread, they are blocked by default in a Thread. Call unblockSignal(sig) if you want to catch them in a Thread.

References _blockedSignals, _unblockedSignals, currentThread(), isRunning(), and thr_add_sig().

Referenced by nidas::dynld::UDPSampleOutput::ConnectionMonitor::ConnectionMonitor(), nidas::core::ServerSocket::ConnectionThread::ConnectionThread(), nidas::core::DerivedDataReader::DerivedDataReader(), nidas::util::McSocketListener::McSocketListener(), nidas::util::McSocketMulticaster< SocketTT >::McSocketMulticaster(), nidas::core::SensorHandler::SensorHandler(), nidas::core::SensorOpener::SensorOpener(), test(), nidas::dynld::RawSampleService::Worker::Worker(), nidas::core::XmlRpcThread::XmlRpcThread(), and nidas::dynld::UDPSampleOutput::XMLSocketListener::XMLSocketListener().

void Thread::cancel ( )
throw (Exception
)
virtual
static const std::string& nidas::util::Thread::currentName ( )
inlinestatic

Convenience routine to return the name for the current thread, or a string indicating that the name of the thread is unknown.

References currentThread(), getName(), and unknownName.

Referenced by nidas::util::Logger::msg_locked().

Thread * Thread::currentThread ( )
static

Return the thread object for the current thread.

Returns null if not found.

Referenced by blockSignal(), currentName(), and unblockSignal().

pthread_t Thread::currentThreadId ( )
static
const std::string & Thread::getFullName ( )
throw (
)

Return a name with a bunch of descriptive fields, specifying whether it is detached, the real-time priority, etc.

References _fullname.

Referenced by pRun(), test(), thr_cleanup(), and thr_cleanup_delete().

pthread_t nidas::util::Thread::getId ( ) const
inlineprotected

References _id, and _mutex.

Referenced by isJoined(), join(), pRun(), and nidas::core::Looper::removeClient().

const std::string & Thread::getName ( ) const
throw (
)
string Thread::getPolicyString ( int  policy)
static

Convenience function to return a string for the given scheduler policy: "Non-RT", "RT:FIFO", "RT:RR" or "RT:Unknown".

References NU_THREAD_FIFO, NU_THREAD_OTHER, and NU_THREAD_RR.

Referenced by nidas::core::DSMSensor::getLooper(), and makeFullName().

void Thread::interrupt ( )
virtual

Interrupt this thread.

This sets a boolean which can be tested with isInterrupted(). It is up to the run() implementation to return when interrupted. This is a "soft" request to terminate the thread.

What follows is a discussion of when to use cancel(), kill(), or interrupt() to terminate a thread.

If you can consistently check the state of isInterrupted() in the run method, and return if it is true, at a time interval which is an acceptable amount of time to wait for the thread to terminate, then using interrupt() should work well.

If the run method does I/O, then things are usually a bit more complicated.

If all I/O is guaranteed to finish quickly, which is a rare situation, or is done with a timeout, such as using select/poll with a timeout before every read/write, then one could still use interrupt() as above, and the thread will terminate within the timeout period.

If the thread does blocking I/O operations, and the I/O might block for a period of time longer than you're willing to wait for the thread to terminate, then you need to use kill(sig) or cancel().

If a signal is sent to the thread with kill(sig) while the thread is blocking on an I/O operation, the I/O will immediately return with an errno of EINTR, and one could then return from the run method, after any necessary cleanup.

However there is a possibility that the signal could be missed. In order to make sure you receive a signal, you must block it, so that any received signals are held as pending, and then atomically unblock it with pselect/ppoll/epoll_pwait before performing the I/O operation.

If you do not use I/O timeouts, or kill(sig) with pselect/ppoll/epoll_pwait, or other tricks such as writing to a pipe that is watched with select/poll in the run method, then using cancel() is the only way to guarantee that your thread will terminate in an acceptable amount of time.

All NIDAS Threads support deferred cancelation. Immediate asynchronous cancellation is not fully supported (and is very hard to get right). Deferred cancelation means that cancellation is delayed until the thread next calls a system function that is a cancellation point. At that point the thread run method will simply terminate without any return value from the system function, and then execute any cleanup methods that may have been registered with pthread_cleanup_push.

A list of cancellation points is provided in the pthreads(7) man page. Cancellation points are typically I/O operations, waits or sleeps.

This immediate thread termination can be a problem if there is a possibility that your objects could be left in a bad state, such as with a mutex locked, though it isn't generally a good practice to hold mutexes during a time-consuming I/O operation, wait or sleep.

One should check the run method to see if the state of the objects is OK if execution stops at any of the cancellation points. Note that logging a message, or writing to cerr is a cancellation point. Typically there is error/exception handling associated with an I/O operation. Ensuring the state is OK upon a cancellation is similar to preparation for a fatal I/O error that requires a return of the run method. One can use setCancelEnabled() to defer cancellation.

One can use pthread_cleanup_push and pthread_cleanup_pop to register cleanup routines that are called when a thread is cancelled if special handling is required.

Implements nidas::util::Runnable.

Reimplemented in nidas::util::McSocketMulticaster< SocketTT >, nidas::util::ThreadRunnable, nidas::util::McSocketListener, nidas::core::ServerSocket::ConnectionThread, nidas::core::Socket::ConnectionThread, nidas::dynld::RawSampleService::Worker, nidas::dynld::UDPSampleOutput::XMLSocketListener, nidas::core::SensorHandler, nidas::core::SampleSorter, nidas::core::SampleBuffer, nidas::dynld::UDPSampleOutput::VariableListWorker, nidas::dynld::raf::SyncServer, nidas::core::DerivedDataReader, nidas::core::SensorOpener, nidas::dynld::XMLConfigService::Worker, nidas::core::SampleOutputRequestThread, and nidas::core::XmlRpcThread.

References _interrupted, and _mutex.

Referenced by nidas::dynld::UDPSampleOutput::close(), nidas::util::McSocket< SocketT >::close(), nidas::core::SampleOutputRequestThread::interrupt(), nidas::core::SensorOpener::interrupt(), nidas::dynld::raf::SyncServer::interrupt(), nidas::core::DSMService::interrupt(), nidas::core::SampleSorter::interrupt(), nidas::core::SamplePipeline::interrupt(), nidas::core::DSMEngine::interrupt(), nidas::util::McSocketListener::interrupt(), nidas::core::SamplePipeline::join(), nidas::core::Looper::removeClient(), and nidas::dynld::UDPSampleOutput::~UDPSampleOutput().

bool Thread::isCancelDeferred ( ) const

Return true if the cancel type of this thread is PTHREAD_CANCEL_DEFERRED.

References _cancel_deferred.

bool Thread::isCancelEnabled ( ) const

Return true if the cancel state of this thread is PTHREAD_CANCEL_ENABLE.

References _cancel_enabled.

virtual bool nidas::util::Thread::isDetached ( ) const
inlinevirtual

Is this a detached thread.

References _detached.

virtual bool nidas::util::Thread::isInterrupted ( ) const
inlinevirtual
virtual bool nidas::util::Thread::isJoined ( ) const
inlinevirtual
virtual bool nidas::util::Thread::isRunning ( ) const
inlinevirtual
int Thread::join ( )
throw (Exception
)
virtual
void Thread::kill ( int  sig)
throw (Exception
)
virtual
Thread * Thread::lookupThread ( pthread_t  id)
static
void Thread::makeFullName ( )
private
Thread& nidas::util::Thread::operator= ( const Thread x)
private

Assignment operator not supported.

Supporting it wouldn't be much problem, since the copy constructor is supported, but there hasn't been a need yet.

int Thread::pRun ( )
privatevirtual
void Thread::registerThread ( )
private

Register this current thread with a static registry of threads by id.

Thread::registerThread (new Thread ("Main"));

Referenced by start().

virtual int nidas::util::Runnable::run ( )
throw (Exception
)
pure virtualinherited
void Thread::setCancelDeferred ( bool  val)
protected

Set the cancel type for this thread.

true means cancel requests are deferred until the next cancellation point. false means they occur instantly. This is protected, it should be called only from a thread's own run method. See the pthreads(7) man page for a list of the cancellation points.

Note: non-deferred canceling is difficult to get right. It has not been tested with this class, and is not recommended.

References _cancel_deferred.

void Thread::setCancelEnabled ( bool  val)
protected

Set the cancel state for this thread - false means cancel requests are ignored.

See pthread_setcancelstate. This is protected, it should be called only from a thread's own run method.

References _cancel_enabled.

bool Thread::setNonRealTimePriority ( )
throw (Exception
)
bool Thread::setRealTimeFIFOPriority ( int  val)
throw (Exception
)
bool Thread::setRealTimeRoundRobinPriority ( int  val)
throw (Exception
)
void Thread::setThreadScheduler ( enum SchedPolicy  policy,
int  priority 
)
throw (Exception
)
void Thread::setThreadSchedulerNolock ( enum SchedPolicy  policy,
int  priority 
)
throw (Exception
)
private
void Thread::sigAction ( int  sig,
siginfo_t *  si,
void *  vptr 
)
staticprivate

References DLOG, getName(), and signalHandler().

Referenced by thr_add_sig().

virtual void nidas::util::Thread::signalHandler ( int  ,
siginfo_t *   
)
inlineprivatevirtual

Signal handler function for this thread.

The default handler just sets _interrupt to true, so that amInterrupted() or isInterrupted() will return true. Derived classes can override this method for custom signal handling. However, derived classes are limited in what they can do in their signal handler. Specifically, from the pthread_cond_signal man page:

"It is not safe to use the pthread_cond_signal() function in a signal handler that is invoked asynchronously."

Therefore do not call Cond::signal() from a signal handler.

Reimplemented in nidas::core::SensorHandler.

References _interrupted.

Referenced by sigAction().

void Thread::start ( )
throw (Exception
)
virtual
int Thread::test ( int  argc,
char **  argv 
)
static
void nidas::util::Runnable::testCancel ( ) const
inlineprotectedinherited

Check if we have been cancelled.

Calls pthread_testcancel. This is protected since it only checks the current thread - i.e. it must be called within the run method. Since it just calls pthread_testcancel, it is a cancellation point.

void Thread::thr_add_sig ( int  sig)
staticprivate

References sigAction().

Referenced by blockSignal(), and unblockSignal().

void Thread::thr_cleanup ( void *  me)
staticprivate

References _mutex, _running, getFullName(), ILOG, and unregisterThread().

Referenced by thr_run().

void Thread::thr_cleanup_delete ( void *  me)
staticprivate
void * Thread::thr_run ( void *  me)
staticprivate

References pRun(), and thr_cleanup().

Referenced by start().

void * Thread::thr_run_detached ( void *  me)
staticprivate

References pRun(), and thr_cleanup_delete().

Referenced by start().

void Thread::unblockSignal ( int  sig)

Install a signal handler and unblock the signal.

The signal handler will log a message about the receipt of the signal at severity LOG_INFO using the nidas::util::Logger. Then, if the signal handler is being invoked from a registered Thread, the virtual method signalHandler() for that Thread will be called.

The signal handler is installed with the sigaction() system call, and will be the action for the given signal in all threads, including the main() thread. If other threads do not wish to take action on a given signal, they should call blockSignal(sig). Or they can define their own signalHandler() method.

After installing the signal handler, the signal is added to those that are unblocked for the thread, or if the Thread is not yet running, the signal will be unblocked in the thread once it runs.

As with blockSignal(), this method is typically called on this Thread before it has started. If this Thread has started, then the signal will only be unblocked if the method is called from this Thread, i.e. from its own run() method.

To install a signal handler, and then block the signal so that it is held as pending until it is later unblocked, typically with pselect(), or sigwaitinfo(), do:

void Thread::run()
{
// get the existing signal mask
sigset_t sigmask;
pthread_sigmask(SIG_BLOCK,NULL,&sigmask);
// remove SIGUSR1 from the mask passed to pselect
sigdelset(&sigmask,SIGUSR1);
for (;;) {
pselect(nfd,&readfds,0,0,0,&sigmask);
...
}
}
...
thread.unblockSignal(SIGUSR1);
thread.blockSignal(SIGUSR1);
thread.start();
...
try {
if (thread.isRunning()) {
thread.kill(SIGUSR1);
thread.join()
}
}

References _blockedSignals, _unblockedSignals, currentThread(), isRunning(), and thr_add_sig().

Referenced by nidas::core::DerivedDataReader::DerivedDataReader(), nidas::core::FsMountWorkerThread::FsMountWorkerThread(), nidas::core::StatusListener::StatusListener(), nidas::core::StatusThread::StatusThread(), nidas::dynld::XMLConfigService::Worker::Worker(), nidas::core::XmlRpcThread::XmlRpcThread(), and nidas::dynld::UDPSampleOutput::XMLSocketListener::XMLSocketListener().

void Thread::unregisterThread ( )
private

Referenced by thr_cleanup(), and thr_cleanup_delete().

void nidas::util::Thread::unsetId ( )
inlineprivate

References _id, and _mutex.

Member Data Documentation

sigset_t nidas::util::Thread::_blockedSignals
private
bool nidas::util::Thread::_cancel_deferred
private
bool nidas::util::Thread::_cancel_enabled
private
bool nidas::util::Thread::_detached
private
Exception* nidas::util::Thread::_exception
private

Exception thrown by run method.

Referenced by join(), pRun(), and ~Thread().

std::string nidas::util::Thread::_fullname
private

Referenced by getFullName(), and makeFullName().

pthread_t nidas::util::Thread::_id
private
bool nidas::util::Thread::_interrupted
private
Mutex nidas::util::Thread::_mutex
mutableprivate
std::string nidas::util::Thread::_name
private

Referenced by getName(), and makeFullName().

bool nidas::util::Thread::_running
private
pthread_attr_t nidas::util::Thread::_thread_attr
private

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

sigset_t nidas::util::Thread::_unblockedSignals
private
std::string Thread::unknownName = std::string("unknown")
staticprivate

Referenced by currentName().


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