/* * MyThread.cpp * Benjamin Bertka - 23306013 * bbertka@mss.icics.ubc.ca * * CICS505 - os6 part B */ #include "MyThread.h" #include "windows.h" #include #include #include #include #include #include /* * this is a method called by each thread to increment thread counter, * then sleep. The current status of threads is printed to stdout * so the race values are viewable by user * @param (LPVOID)param - This is an int data[5] that holds public info * PRE: param is valid * POST: data[] is updated with values */ unsigned __stdcall MyThread::threadWork(LPVOID param){ int * data = (int *)param; int k; for(int i = 0; i < data[3]; ++i){ k = data[1]; data[0]+=k; //data[0] += 1; Sleep(data[2]); cout << "thread: " << data[4] << " counter: " << data[0] << " interval: " << data[1] << endl; } _endthreadex(0); return 0; } /* * Constructor which sets defaults */ MyThread::MyThread(){ this->lpThreadAttributes = NULL; this->dwStackSize = 0; this->lpParameter = NULL; this->dwCreationFlags = 0; } /* * Sets values for public and private thread data */ void MyThread::setParameter(int id, int in, int sleep, int increm){ this->id = id; this->sleepTime = sleep; this->increment = increm; this->value = in; this->counter = 0; this->lpParameter = (LPVOID)in; this->data[0] = this->counter; this->data[1] = this->increment; this->data[2] = this->sleepTime; this->data[3] = this->value; this->data[4] = this->id; } /* * A wrapper for the _beginthreadex * returns true of no problems, false otherwise */ bool MyThread::create(){ /* This handle is public */ this->handle = (HANDLE)_beginthreadex(this->lpThreadAttributes, this->dwStackSize, threadWork, &this->data, this->dwCreationFlags, &this->threadID); if(this->handle == NULL){ ExitThread(ERROR); //exit of problem with handle return false; }else{ return true; } return true; } /* * prints useful data */ void MyThread::print(){ cout << "print thread goal: "<< (int)this->lpParameter << endl; cout << "print thread sleep: " << this->sleepTime << endl; cout << "print thread interval: " << this->increment << endl; cout << "print thread counter: " << this->counter <threadID <handle); } /* * waits for thread */ void MyThread::wait(){ WaitForSingleObject(this->handle,10000); }