Main Page   Namespace List   Class Hierarchy   Compound List   Namespace Members   Compound Members  

Thread Class Reference

#include <Thread.h>

Inheritance diagram for Thread:

NonCopyable Cancelable Runnable List of all members.

Public Methods

 Thread ()
virtual ~Thread () throw ()
 Destroy a Thread.

bool operator== (const Thread &t) const
 Comparison operator.

bool operator!= (const Thread &t) const
 Comparison operator.

bool operator== (const Reference &r) const
 Comparison operator.

bool operator!= (const Reference &r) const
 Comparison operator.

bool join (unsigned long timeout=0)
virtual void run () throw ()
void run (const RunnableHandle &task)
void run (Runnable *task)
void start ()
void setPriority (Priority p) throw ()
Priority getPriority () throw ()
virtual bool interrupt () throw ()
virtual bool isCanceled ()
virtual void cancel ()
bool isDaemon () throw ()
void setDaemon (bool flag)

Static Public Methods

bool interrupted () throw ()
bool canceled () throw ()
void sleep (unsigned long timeout)
void yield () throw ()
Reference current () throw ()

Detailed Description

Author:
Eric Crahen <crahen@cse.buffalo.edu>
Date:
<2002-07-13T10:10:33-0400>
Version:
2.2.9
A Thread is a special kind of Runnable object that represents a thread of execution in a program. It allows tasks to be started an run concurrently.

There are two kinds of threads. Non-daemon threads and daemon threads. Non-daemon threads must be joined. Non-daemon threads must be joined, the lifetime of its task must be enclosed by the lifetime of the Thread object.

 {
   MyThread t;         // Thread object's lifetime begins
   t.run();            // Task's effective lifetime begins
   t.join();           // Task's effective lifetime ends 
 }                     // Thread object's lifetime begins 

Daemon threads cannot be joined, they have the special property of allowing the effective lifetime of its task to exceed the lifetime of the Thread object.

 {
   MyThread t;         // Thread object's lifetime begins
   t.setDaemon(true);
   t.run();            // Task's effective lifetime begins   
 }                     // Thread object's lifetime begins 

                       // Task's effective lifetime ends 

Using:

There are two way to use threads. The first is to extend the Thread class. This creates a heavy-wieght task; because the task is always associated with the overhead of a specific thread. Afterall, it is a Thread.

 class MyThread : public Thread {
 public:

  virtual ~MyThread() throw() { }

  virtual void run() throw() {

    // perform task

  }

 };

 int main() {

   try {

     MyThread t;
     t.start();

   } catch(Synchronization_Exception&) {  
     std::cerr << "error starting thread!" << std::endl;
   }

 }

Such a thread can be run using the start() function.

 MyThread t;             // Create the thread
 t.start();              // run the task
 t.join();               // wait for completion

The second way is create extend the Runnable class. This creates a light-weight task; because it is not associated with any one specific thread. This is an application of the Command pattern.

 class MyRunnable : public Runnable {
 public:

   virtual ~MyRunnable() throw() { }

  virtual void run() throw() {

    // perform task

  }

 };

When Runnable objects are be submitted to Threads for execution they are wrapped with a reference counting object (called Handle) to simplify the task of keeping track of them. These wrappers are created for you automatically using the RunnablePtr() function.

 // Submit a series of tasks to different threads

 Thread t[NUM_THREADS];

 for(int i=0; i<NUM_THREADS; ++i)
   task.run( RunnablePtr(new MyTask()) );

An instance of a Runnable class can also be shared and submitted to several threads; rather than creating a new Runnable object for each thread.

 // Submit a single task to different threads

 Thread t[NUM_THREADS];

 Handle<MyTask> task = RunnablePtr(new MyTask());

 for(int i=0; i<NUM_THREADS; ++i)
   task.run( task );

See also:
Handle , CancelableTask
Interrupting:

Threads are interruptible. Each thread has an interrupted status associated with it. This is set with the interrupt() method. A thread with an interrupted status will throw an Interrupted_Exception if it attempts a blocking operation (sleep(), Lockable::acquire(), Waitable::wait(), ...) and its interrupted status will be reset. Calling Thread::interrupted() will allow the currently executing thread to check and reset its interrupted status in a single operation.

Canceling:

Threads are Cancelable objects. A Thread extends the usual cancelation semantics to have the following meaning.

Disabling

A cancel()ed thread is placed into both interrupted and canceled status. This allows interrupt sensative code to respond to cancel() naturally. The Thread::canceled() function will report the canceled status of a thread and clear its interrupted status. However, canceled status can never be removed.

Exiting

A thread that has been cancel()ed is not forced to exit. It behaves as thread that has been interrupted would. By canceling a thread, it is sent a specific message that a request for it to exit has arrived. The thread may then respond by performing a graceful shutdown, performing whatever work is neccessary to do so.

By implementing the Cancelable interface to work with the interruption mechanism, it is possible to write very elegant code and to create some flexible task oriented frameworks.


Constructor & Destructor Documentation

Thread  
 

Create a new thread object that can execute tasks in another thread of execution

Exceptions:
Initialization_Exception  - thrown if there are not enough resources to do this


Member Function Documentation

virtual void cancel   [virtual]
 

Set the cancelation and interruption status of this thread.

Exceptions:
InvalidOp_Exception  thrown if a thread attempts to cancel itself

Implements Cancelable.

bool canceled   throw () [static]
 

Tests whether the current Thread has been canceled, and clears the interrupted status.

Returns :
bool true only if the Thread::cancel() has been invoked.

Reference current   throw () [static]
 

Get a reference to the currently executing thread.

Returns :
Reference - object representing the current thread.

Priority getPriority   throw ()
 

Get the priority of this Thread.

Returns :
Priority

virtual bool interrupt   throw () [virtual]
 

Interrupts this thread.

If this thread is blocked when this method is called, the thread will abort that blocking operation with an Interrupted_Exception.

Otherwise, the interrupted status of the thread is set. This status is cleared by one of two methods. The first is by attempting another blocking operation; this will clear the interrupted status and immediately abort the operation with an Interrupted_Exception. The second is to call isInterrupted() from the context of this thread.

A thread is never started in an interrupted state. The interrupted status of a thread will be discarded when the thread starts.

Interrupting a thread that is no longer running will have no effect other than setting the interrupt status permanently. When a thread exits, that status can no longer be cleared.

Returns :
bool true only if the Thread was interrupted successfully and it is not the current thread and it is not blocked on a synchronization object. This indicates it may be blocked by a system call, or not at all. A user can extend the Thread class to take advantage of this hint to implement i/o interruption for thier system.

bool interrupted   throw () [static]
 

Tests whether the current Thread has been interrupt()ed, clearing its interruption status.

Returns :
bool true if the Thread was interrupted, otherwise false

virtual bool isCanceled   [virtual]
 

Tests whether this thread has been canceled. If called from the context of this thread, the interrupted status is cleared.

Returns :
bool true if the Thread was canceled, otherwise false
Postcondition:
There is no serlization garuntee with this method, Its possible for a thread to be canceled immediately after this functions returns.

Implements Cancelable.

bool isDaemon   throw ()
 

Tests if this thread is a daemon thread.

Returns :
bool - true if this thread is a daemon thread.

bool join unsigned long    timeout = 0
 

Wait for the thread represented by this object to exit. Only one thread can wait on any other thread.

Parameters:
timeout  - maximum amount of time (milliseconds) this method could block. A timeout of 0 will block indefinently.
Exceptions:
Deadlock_Exception  thrown if thread attempts to join itself
InvalidOp_Exception  thrown if the thread cannot be joined
Interrupted_Exception  thrown if the joining thread has been interrupt()ed

void run Runnable   task [inline]
 

Convience method

See also:
Thread::run(const RunnableHandle&)

void run const RunnableHandle &    task
 

From the context of this Thread, execute the task defined by the given Runnable object.

Exceptions:
InvalidOp_Exception  thrown if a thread has already been assigned a task and is running; or if this thread has already been used to run a task.
Synchronization_Exception  thrown if there is some other error starting the thread

virtual void run   throw () [virtual]
 

This can be implemented by subclasses to create a thread with a built in task. The default behavior is for the task to just return immediately, doing nothing.

Implements Runnable.

void setDaemon bool    flag
 

Change the status of this thread so that is now treated as a daemon thread. A daemon thread should not be joined, it will execute normally and its destructor can safely be invoked without first join()ing it. It will be join()ed by ZThreads when the program exits.

Parameters:
bool  - flag, set to daemon if true, otherwise set back to a normal user thread that can be joined.
Exceptions:
InvalidOp_Exception  thrown if the status cannot be changed.

void setPriority Priority    p throw ()
 

Change the priority of this Thread. This will change the actual priority of the thread when the OS supports it. If there is no real priority support, it's simulated.

Parameters:
p  - new Priority

void sleep unsigned long    timeout [static]
 

Put the currently executing thread to sleep for a given amount of time.

Parameters:
timeout  - maximum amount of time (milliseconds) this method could block
Exceptions:
Interrupted_Exception  thrown if this wait was interrupt()ed

void start  
 

From the context of this Thread, this method will run the Threads run() method. The default implementation for the run() method will throw an exception and exit immediately. However, subclasses can provide thier own, more useful, implementation of that method.

Exceptions:
Synchronization_Exception  thrown if there is an error starting the thread

void yield   throw () [static]
 

Cause the currently executing thread to yield, allowing the scheduler to assign some execution time to another thread.


The documentation for this class was generated from the following file:
Generated on Tue Aug 27 07:43:15 2002 for ZThread by doxygen1.2.17