/////////////////////////////////////////////////////////////// // Threads.cpp - Create and run threads // // ver 1.0 // // Language: standard C++ // // Platform: Dell Dimension T7400, Windows 7, SP #1 // // Application: Resource for DO projects // // Author: Jim Fawcett, CST 4-187, Syracuse University // // jfawcett@twcny.rr.com, (315) 443-3948 // /////////////////////////////////////////////////////////////// #include #include #include #include "Threads.h" //----< ThreadBase constructor >------------------------------- ThreadBase::ThreadBase() { doLog("constructing ThreadBase"); hThread = (HANDLE)_beginthreadex ( NULL, // default security properties 0, // default stack size threadOps, // function that thread runs (void*)this, // static function can access thread members CREATE_SUSPENDED, // start thread suspended, call start() to run &_threadID // OS thread identifier ); if(hThread == 0) throw std::exception("\n failed to create thread"); } //----< start thread running >--------------------------------- void ThreadBase::start() { doLog("starting child thread"); ResumeThread(hThread); } //----< this is where the derived processing gets to run >----- unsigned int ThreadBase::threadOps(void* pThis) { doLog("in threadOps"); ((ThreadBase*)pThis)->run(); return 0; } //----< wait for child thread to exit >------------------------ void ThreadBase::join() { doLog("waiting for thread exit"); ::WaitForSingleObject(hThread,INFINITE); doLog("wait over - thread exited"); } //----< test stub >-------------------------------------------- #ifdef TEST_THREADS /////////////////////////////////////////////////////////////// // demonstration derived class class ThreadDemo : public ThreadBase { public: ThreadDemo(std::string& Message); private: gLock<1> tLock; virtual void run(); std::string& Msg; }; //----< demo thread constructor >------------------------------ ThreadDemo::ThreadDemo(std::string& Message) : Msg(Message) {} //----< here is where what you want to happen happens >-------- void ThreadDemo::run() { tLock.lock(); std::cout << "\n " << Msg.c_str(); std::cout.flush(); Msg = ""; tLock.unlock(); std::cout << "\n hello back from child"; for(size_t i=0; i<25; ++i) { tLock.lock(); Msg += '0'; tLock.unlock(); ::Sleep(2); } std::cout << "\n child exiting"; } //----< test stub >-------------------------------------------- int main() { std::cout << "\n Demonstrating Basic Thread Processing in Thread Class"; std::cout << "\n =======================================================\n"; std::string Message = "hello from parent"; { ThreadDemo td(Message); td.start(); gLock<1> pLock; for(size_t i=0; i<25; ++i) { pLock.lock(); Message += '1'; pLock.unlock(); ::Sleep(1); } td.join(); } std::cout << "\n " << Message.c_str(); std::cout.flush(); std::cout << "\n parent exiting\n\n"; } #endif