///////////////////////////////////////////////////////////////////// // threads.cpp - Abstract class supporting creation of threads // // ver 1.3 // // Language: Visual C++, ver 6.0, SP 5 // // Platform: Dell Dimension 8100, Win 2000 Pro, SP 2 // // Application: CSE691/791 - SWM&A Demonstration // // Author: Jim Fawcett, CST 2-187, Syracuse Univ // // (315) 443-3948, jfawcett@twcny.rr.com // // // ///////////////////////////////////////////////////////////////////// #include "threads.h" //----< Win32 thread is created here >------------------------------- void thread::start() { th = (HANDLE)_beginthreadex( NULL, // default security attributes 0, // default stack size threadProc, // thread processing function (void*)this, // pointer to this thread object 0, // create thread in running state &threadID // thread identifier assigned by OS ); } //----< destroy thread >--------------------------------------------- thread::~thread() { CloseHandle(th); } //----< thread proc wrapper for derived class's run function >------- unsigned int __stdcall thread::threadProc(void *pSelf) { ((thread*)pSelf)->run(); return 0; } //----< wait until thread terminates >------------------------------- void thread::wait() { WaitForSingleObject(th,INFINITE); } // //----< test stub >-------------------------------------------------- #ifdef TEST_THREADS #include "lockingPtr.h" using namespace std; /////////////////////////////////////////////////////////////// // first example of a derived thread class class test1Thread : public thread { protected: virtual void run(); }; void test1Thread::run() { int i; for(i=0; i<10; i++) { canSuspend(false); // avoid deadlock if this thread is suspended safeOut sout(std::cout); sout << locker << "\n running test1Thread " << (long)thread::threadID << '\n' << unlocker; canSuspend(true); // allow thread to be suspended since unlocked sleep(20); } } // /////////////////////////////////////////////////////////////// // second example of a derived thread class // - this one provides a member function to supply the // thread proc with a string parameter class test2Thread : public thread { public: void setString(const string &s) { _str = s; } protected: virtual void run() { int i; safeOut sout(cout); sout << locker << "\n " << _str << "\n" << unlocker; for(i=0; i<10; i++) { sout << locker << "\n running test2Thread " << (long)thread::threadID << '\n' << unlocker; sleep(20); } } private: string _str; }; void main() { cout << "\n Demonstrating thread class " << "\n ============================\n"; cout.flush(); test1Thread t1; t1.start(); test2Thread t2; t2.setString("a user defined string passed to thread"); t2.start(); Sleep(50); // let both threads run awhile while(!t1.suspend()) ; // suspend t1 until t2 finishes t2.wait(); t1.resume(); // now restart t1 t1.wait(); cout << "\n\n"; } #endif