
1.6.2 C++ Class Thread for Pthreads
Listing 1.7 shows C++ classes Runnable and Thread for Pthreads.
Method run() can return a value.
A call to T.join() blocks the caller until thread T’s run() method completes. Method
join() returns the value that was returned by run().
Class Runnable simulates Java’s Runnable interface.
C++ Threads can be created on the heap or on the stack. (Java Thread objects, like
other Java objects, are never created on the stack.)
Java has a built-in join() operation that is useful in Java when one thread needs to
make sure that other threads have completed before, say, accessing their results.
Java’s run() method cannot return a value so results must be obtained some other way.
Listing 1.7 shows C++ classes Runnable and Thread for Pthreads.
The program in Listing 1.6 illustrates the use of C++ classes Thread and Runnable. It is
designed to look like the Java programs in Listings 1-1 and 1-2.
class Runnable {
public:
virtual void* run() = 0;
virtual ~Runnable() = 0;
};
Runnable::~Runnable() {} // a function body is required for pure virtual destructors
class Thread {
public:
Thread(auto_ptr<Runnable> runnable_, bool isDetached = false);
Thread(bool isDetached = false);
virtual ~Thread();
void start(); void* join();
private:
pthread_t PthreadThreadID; // thread ID
bool detached; // true if thread created in detached state; false otherwise
pthread_attr_t threadAttribute;
auto_ptr<Runnable> runnable;
Thread(const Thread&);
const Thread& operator= (const Thread&);
void setCompleted();
void* result; // stores return value of run()
virtual void* run() {}
static void* startThreadRunnable(void* pVoid);
static void* startThread(void* pVoid);
void PrintError(char* msg, int status, char* fileName, int lineNumber);
};
Listing 1.7 C++/Pthreads classes Runnable and Thread.