#ifndef THREADS_H #define THREADS_H /////////////////////////////////////////////////////////////// // Threads.h - 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 // /////////////////////////////////////////////////////////////// /* * 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 #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: pthread_t ntid; private: virtual void run()=0; static void* threadOps(void* pArg); }; inline ThreadBase::~ThreadBase() {} class Lock { public: Lock(); ~Lock(); void lock(); void unlock(); private: pthread_mutex_t mutex; }; inline Lock::Lock() { pthread_mutex_init(&mutex,0); } inline Lock::~Lock() { pthread_mutex_destroy(&mutex); } inline void Lock::lock() { pthread_mutex_lock(&mutex); } inline void Lock::unlock() { pthread_mutex_unlock(&mutex); } template class gLock { public: gLock(); ~gLock(); void lock(); void unlock(); private: static pthread_mutex_t mutex; static unsigned int refCount; }; template pthread_mutex_t gLock::mutex; template unsigned int gLock::refCount = 0; template gLock::gLock() { if(refCount == 0) { pthread_mutex_init(&mutex, NULL); doLog("Creating global mutex"); } ++refCount; } template gLock::~gLock() { if(--refCount == 0) { pthread_mutex_destroy(&mutex); doLog("destroying global mutex"); } } template void gLock::lock() { pthread_mutex_lock(&mutex); } template void gLock::unlock() { pthread_mutex_unlock(&mutex); } #endif