| CODE |
class MyMutex { public: MyMutex() { CON_MUTEX(mutex);} ~MyMutex() { DEL_MUTEX(mutex);} private: MUTEX mutex; // MUTEXT is a typedef of the unerlying C mutex object. // The actual value will depend on your C lib pthread_mutex or windows mutex etc. MyMutex(const MyMutex& copy); // No Definition to stop copying. MyMutex& operator=(const MyMutex& copy); // We could go extreme and stop programmers getting a pointer to a mutex // But I don't see and real value in that. // If people really want to go out of their way to defeat somthing they will // always be able to do it. We are not trying to stop malisious attempts at // subversion we are just trying to protect ourselves from accidental missuse. }; |
| CODE |
void MyMutex::lock(); // Attempt to lock the mutex. If the mutex is already locked // the suspend the thread until the lock is release. // If the same thread has already locked the mutex the action performed // is defined by the current policy void MyMutex::unlock(); // If one or more threads are suspended waiting for the mutex pick one // according to the appropriate policy and activate it (giving it the lock). // otherwise simply unlock the mutex. NB Only the thread that locked // the mutex should be allowed to unlock it (probably). bool MyMutex::tryLock(time_t x = 0); // Like lock. But if the mutex is already locked and is not released in time 't' // then return false. If the mutex was succesfully locked return true. |
| CODE |
| class MyMutex { public: MyMutex() { CON_MUTEX(mutex);} ~MyMutex() { DEL_MUTEX(mutex);} private: MUTEX mutex; friend class MyLock; void lock() {LOCK_MUTEX(mutex);} void unlock() {UNLOCK_MUTEX(mutex);} MyMutex(const MyMutex& copy); // No Definition to stop copying. MyMutex& operator=(const MyMutex& copy); }; class MyLock { public: MyLock(MyMutex& m): mutex(m) {mutex.lock();} ~MyLock() {mutex.unlock();} private: MyMutex& mutex; }; |
| CODE |
| void func1() { static MyMutex mutex; MyLock lock(mutex); // Do Somthing important. } |
| CODE |
| class MySingleThreadedClass { public: void func1(); void func2(); private: MyMutex m_mutex; }; void MySingleThreadedClass::func1() { MyLock lock(m_mutex); // STUFF } void MySingleThreadedClass::func2() { MyLock lock(m_mutex); // Other Stuff } |
| QUOTE (raduking @ Nov 8 2005, 12:18 PM) |
| I think you need the copy constructor defined otherwise the linker won't be able to link the following line: public: MyLock(MyMutex& m): mutex(m) {mutex.lock();} |