/////////////////////////////////////////////////////////////// // Threads.cpp - Create and run threads // // ver 1.0 // // Language: standard C++ // // Platform: Sony Vaio Series L, Kubuntu 11.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"); } //----< this is where the derived processing gets to run >----- void* ThreadBase::threadOps(void* pThis) { doLog("in threadOps"); reinterpret_cast(pThis)->run(); return 0; } //----< start thread running >--------------------------------- void ThreadBase::start() { doLog("starting child thread"); int err = pthread_create(&ntid, NULL, ThreadBase::threadOps, this); if(err != 0) { throw std::exception(); } else doLog("child started"); } //----< wait for child thread to exit >------------------------ void ThreadBase::join() { doLog("waiting for thread exit"); pthread_join(ntid,0); 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() { doLog("in 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(); usleep(2000); } 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(); usleep(1000); } doLog("about to join"); td.join(); } std::cout << "\n " << Message.c_str(); std::cout.flush(); std::cout << "\n parent exiting\n\n"; } #endif