#ifndef THREADS_H #define THREADS_H /////////////////////////////////////////////////////////////// // Threads.h - 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 // /////////////////////////////////////////////////////////////// /* * Package Operations: * =================== * Two classes are defined in this package, a base class ThreadBase * and a demonstraton derived class ThreadDemo. If a the child thread * fails to start, a std::exception object will be thrown, which client * code should be prepared to catch. */ /* * Required Files: * --------------- * Thread.h, Thread.cpp * * Build Process: * -------------- * cl /EHa /DTEST_THREAD Thread.cpp * * Maintenance History: * -------------------- * ver 1.0 : 19 Feb 12 * - first release */ #include #include //----< debug logger >----------------------------------------- inline void doLog(const char* pChar) { #ifdef DOLOG std::cout << "\n " << pChar; #endif } /////////////////////////////////////////////////////////////// // base thread class class ThreadBase { public: ThreadBase(); virtual ~ThreadBase(); void start(); void join(); protected: ::HANDLE hThread; unsigned int _threadID; private: virtual void run()=0; static unsigned int __stdcall threadOps(void* pArg); }; inline ThreadBase::~ThreadBase() { CloseHandle(hThread); } class Lock { public: Lock(); ~Lock(); void lock(); void unlock(); private: ::HANDLE hMutex; }; inline Lock::Lock() { hMutex = CreateMutexA ( NULL, // security attributes false, // won't start locked NULL // no name, so create anonymous mutex ); if(hMutex == NULL) throw std::exception("mutex creation failed"); } inline Lock::~Lock() { CloseHandle(hMutex); } inline void Lock::lock() { ::WaitForSingleObject(hMutex, INFINITE); } inline void Lock::unlock() { ReleaseMutex(hMutex); } template class gLock { public: gLock(); ~gLock(); void lock(); void unlock(); private: static ::HANDLE hMutex; static unsigned int refCount; }; template ::HANDLE gLock::hMutex; template unsigned int gLock::refCount = 0; template gLock::gLock() { hMutex = CreateMutexA ( NULL, // security attributes false, // won't start locked NULL // no name, so create anonymous mutex ); if(hMutex == NULL) throw std::exception("mutex creation failed"); if(refCount == 0) doLog("Creating global mutex"); ++refCount; } template gLock::~gLock() { if(--refCount == 0) { CloseHandle(hMutex); doLog("closing global mutex handle\n"); } } template void gLock::lock() { ::WaitForSingleObject(hMutex, INFINITE); } template void gLock::unlock() { ReleaseMutex(hMutex); } #endif