_DCE Pthreads versus NT Threads_ by Michael Yam Listing One /*---- testptf.cpp exercise some of PTFs classes -----*/ #include "pt\ptf.h" #include "pt\pttf.h" #include #include // Global condition variable and counter. Program ends when gCounter <= 0. PTTSafeType gCounter; PTCondVar gWatchEvent; // Simple classes: increment thread, decrement thread // and watch thread. Uses PTObjects ctor and dtor. class IncThread : public PTObject { public: int runPThread(); }; class DecThread : public PTObject { public: int runPThread(); }; class WatchThread : public PTObject { public: int runPThread(); }; // Implement virtual runPThread() member for all three thread classes. int IncThread::runPThread() { while(gCounter > 0) { ++gCounter; // thread-safe increment printf ("Inc Thread tid: %u gCounter = %d\n", tid(), (int)gCounter); #if defined (_HPUX_SOURCE) || defined (_POSIX_SOURCE) yield(); // HP-UX quantums can be large #endif } return gCounter; } int DecThread::runPThread() { // wait for signal from watch thread before starting. gWatchEvent.timedWait(); while((int)gCounter > 0) { --gCounter; // thread-safe decrement printf ("Dec Thread tid: %u gCounter = %d\n", tid(), (int)gCounter); #if defined (_HPUX_SOURCE) || defined (_POSIX_SOURCE) yield(); // HP-UX quantums can be large #endif } return gCounter; } int WatchThread::runPThread() { PTCondVar sleepEvent; DecThread decThread1; DecThread decThread2; // threads are started but not yet signaled. decThread1.start(); decThread2.start(); while((int)gCounter > 0) { printf ("Watch Thread tid: %u gCounter = %d\n", tid(), (int)gCounter); if (gCounter > 1000) { // wake one dec thread if counter is over arbitrary limit. gWatchEvent.signal(); } sleepEvent.timedWait (3); // nap for 3 secs } decThread1.join(); decThread2.join(); return gCounter; } int main() { gCounter = 500; // arbitrary start count; IncThread incThread; WatchThread watchThread; if (watchThread.isValid()) watchThread.start(); if (incThread.isValid()) incThread.start(); watchThread.join(); incThread.join(); printf ("gCounter = %d\n", (int)gCounter); return 0; }