MutexClass.cpp
Go to the documentation of this file.
00001 //
00002 // MutexClass.cpp: implementation file
00003 //
00004 // Copyright (C) Walter E. Capers.  All rights reserved
00005 //
00006 // This source is free to use as you like.  If you make
00007 // any changes please keep me in the loop.  Email them to
00008 // walt.capers@comcast.net.
00009 //
00010 // PURPOSE:
00011 //
00012 //  To implement mutexes as a C++ object
00013 //
00014 // REVISIONS
00015 // =======================================================
00016 // Date: 10.25.07        
00017 // Name: Walter E. Capers
00018 // Description: File creation
00019 //
00020 // Date:
00021 // Name:
00022 // Description:
00023 //
00024 //
00025 #include <blort/ThreadObject/Thread.h>
00026 
00027 CMutexClass::CMutexClass(void)
00028 :m_bCreated(TRUE)
00029 {
00030 #ifdef WINDOWS
00031    m_mutex = CreateMutex(NULL,FALSE,NULL);
00032    if( !m_mutex ) m_bCreated = FALSE;
00033 #else
00034    pthread_mutexattr_t mattr;
00035 
00036    pthread_mutexattr_init( &mattr );
00037    pthread_mutex_init(&m_mutex,&mattr);
00038 
00039 #endif
00040 
00041 }
00042 
00043 CMutexClass::~CMutexClass(void)
00044 {
00045 #ifdef WINDOWS
00046         WaitForSingleObject(m_mutex,INFINITE);
00047         CloseHandle(m_mutex);
00048 #else
00049         pthread_mutex_lock(&m_mutex);
00050         pthread_mutex_unlock(&m_mutex);
00051         pthread_mutex_destroy(&m_mutex);
00052 #endif
00053 }
00054 
00055 void
00056 CMutexClass::Lock()
00057 {
00058         ThreadId_t id = CThread::ThreadId();
00059         if(CThread::ThreadIdsEqual(&m_owner,&id) )
00060                 return; // the mutex is already locked by this thread
00061 #ifdef WINDOWS
00062         WaitForSingleObject(m_mutex,INFINITE);
00063 #else
00064         pthread_mutex_lock(&m_mutex);
00065 #endif
00066         m_owner = CThread::ThreadId();
00067 }
00068 
00069 void 
00070 CMutexClass::Unlock()
00071 {
00072         ThreadId_t id = CThread::ThreadId();
00073         if( ! CThread::ThreadIdsEqual(&id,&m_owner) )
00074                 return; // on the thread that has locked the mutex can release 
00075                     // the mutex
00076 
00077         memset(&m_owner,0,sizeof(ThreadId_t));
00078 #ifdef WINDOWS
00079         ReleaseMutex(m_mutex);
00080 #else
00081         pthread_mutex_unlock(&m_mutex);
00082 #endif
00083 }
00084 
00085 void
00086 CMutexClass::Wait()
00087 {
00088         Lock();
00089         Unlock();
00090 }
00091 
00092 


blort
Author(s): Thomas Mörwald , Michael Zillich , Andreas Richtsfeld , Johann Prankl , Markus Vincze , Bence Magyar
autogenerated on Wed Aug 26 2015 15:24:12