#include #include using namespace wkgl; /////////////////////////////////////////////////////////////////////////////// //Prototypes void fib( void* param ); /////////////////////////////////////////////////////////////////////////////// //Represents a parameter passed to Thread::start(). struct FIBPARAM { int ntimes; //The nuber of times to loop. long fib; //The ending Fibinocci number. char *prefix; //Label associated with this thread. }; /////////////////////////////////////////////////////////////////////////////// //Main funcion. void main() { FIBPARAM fp1 = { 30, 0, "Fib1 " }; //The parameter for fib1 FIBPARAM fp2 = { 10, 0, "Fib2 " }; //The parameter for fib2 Thread fib1( fib ); //Thread that runs the fib function Thread fib2( fib ); //Thread that runs the fib function ThreadGroup tg; //Holds a group of threads. tg.addThread( &fib1 ); //Add fib1 to the thread group tg.addThread( &fib2 ); //Add fib2 to the thread group fib1.start( &fp1 ); //Start fib1 fib2.start( &fp2 ); //Start fib2 tg.waitForCompletion(); //Wait for all threads to complete //Output the calculations. cout << "Fib1 calculated: " << fp1.fib << "\nFib2 calculated: " << fp2.fib << endl; return; } /////////////////////////////////////////////////////////////////////////////// //fib calculates fibanacci numbers. It expects a param to point to a FIBPARAM. void fib( void *param ) { //Declare the holder variables. long f1 = 1, f2 = 1, f; //Ouput that the thread is starting. cout << ((FIBPARAM*)param)->prefix << "Starting..." << endl; //Loop the number of times found in param. for ( int i = 0; i < ((FIBPARAM*)param)->ntimes; i++ ) { //Sleep a random period between 0 and 200 milliseconds Thread::sleep( rand() % 200 ); //Calculate the fibanacci number. f = f1 + f2; f1 = f2; f2 = f; } //Set the fib value of the param to the calculated number. ((FIBPARAM*)param)->fib = f; //Output that the thread is done. cout << ((FIBPARAM*)param)->prefix << "Done!!" << endl; }