///////////////////////////////////////////////////////////////////// // thrdsWithProc.cpp - class supporting creation of threads // // ver 1.2 // // 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 "thrdsWithProc.h" #include using namespace std; //----< 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)->_proc.run(); return 0; } //----< wait until thread terminates >------------------------------- void thread::wait() { WaitForSingleObject(th,INFINITE); } // //----< test stub >-------------------------------------------------- #ifdef TEST_THRDSWITHPROC #include "lockingPtr.h" using namespace std; class appProc1 : public processing { public: void run() { safeOut out(cout); for(int i=0; i<10; i++) out << locker << "\n thread #1: " << _str << unlocker; } void setString(const string &s) { _str = s; } private: string _str; }; class appProc2 : public processing { public: void run() { safeOut out(cout); for(int i=0; i<10; i++) out << locker << "\n thread #2: " << _str << unlocker; } void setString(const string &s) { _str = s; } private: string _str; }; void main() { cout << "\n Demonstrating thread with processing class " << "\n ============================================\n"; cout.flush(); safeOut out(cout); appProc1 proc1; proc1.setString("a short message"); thread t1(proc1); t1.start(); appProc2 proc2; proc2.setString("a somewhat longer, and rather boring, message"); thread t2(proc2); t2.start(); t1.wait(); t2.wait(); out << "\n\n"; } #endif