1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
|
/*
* Modification History
*
* 2001-January-11 Jason Rohrer
* Created.
*
* 2001-January-27 Jason Rohrer
* Made printing in threads thread-safe.
*/
#include "BinarySemaphore.h"
#include "Semaphore.h"
#include "Thread.h"
#include "ThreadSafePrinter.h"
#include <stdio.h>
/**
* Thread that waits on a semaphore.
*
* @author Jason Rohrer
*/
class WaitingThread : public Thread {
public:
WaitingThread( int inID, Semaphore *inSemaphore );
// override the run method from PThread
void run();
private:
Semaphore *mSemaphore;
int mID;
};
inline WaitingThread::WaitingThread( int inID, Semaphore *inSemaphore )
: mID( inID ), mSemaphore( inSemaphore ) {
}
inline void WaitingThread::run() {
for( int i=0; i<10; i++ ) {
ThreadSafePrinter::printf( "%d waiting for signal %d...\n", mID, i );
mSemaphore->wait();
ThreadSafePrinter::printf( "%d received signal %d.\n", mID, i );
}
}
/**
* Thread that signals on a semaphore.
*
* @author Jason Rohrer
*/
class SignalingThread : public Thread {
public:
SignalingThread( Semaphore *inSemaphore );
// override the run method from PThread
void run();
private:
Semaphore *mSemaphore;
};
inline SignalingThread::SignalingThread( Semaphore *inSemaphore )
: mSemaphore( inSemaphore ) {
}
inline void SignalingThread::run() {
for( int i=0; i<5; i++ ) {
sleep( 5000 );
ThreadSafePrinter::printf( "Signaling 20 times\n" );
for( int j=0; j<20; j++ ) {
mSemaphore->signal();
}
}
}
int main() {
int i;
Semaphore *semph = new Semaphore();
SignalingThread *threadS = new SignalingThread( semph );
WaitingThread **threadW = new WaitingThread*[10];
for( i=0; i<10; i++ ) {
threadW[i] = new WaitingThread( i, semph );
threadW[i]->start();
}
threadS->start();
for( i=0; i<10; i++ ) {
threadW[i]->join();
delete threadW[i];
}
threadS->join();
delete semph;
delete threadS;
delete [] threadW;
return 0;
}
|