00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029 #include "precomp.h"
00030 #include "mutex.h"
00031 #include "exception.h"
00032
00033 #ifndef WIN32
00034
00035
00036 extern "C"
00037 {
00038 #ifdef __FreeBSD__
00039 int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int kind);
00040 #else
00041 int pthread_mutexattr_setkind_np(pthread_mutexattr_t *attr, int kind);
00042 #endif
00043 }
00044 #endif
00045
00047
00048
00049 CL_Mutex::CL_Mutex()
00050 {
00051 #ifdef WIN32
00052 InitializeCriticalSection(&critical_section);
00053 #else
00054 pthread_mutexattr_t attr;
00055 pthread_mutexattr_init(&attr);
00056 #ifdef __FreeBSD__
00057 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
00058 #else
00059 #if PTHREAD_MUTEX_RECURSIVE_NP
00060 pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE);
00061 #else
00062 pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
00063 #endif
00064 #endif
00065 pthread_mutex_init(&handle, &attr);
00066 pthread_mutexattr_destroy(&attr);
00067 #endif
00068 }
00069
00070 CL_Mutex::~CL_Mutex()
00071 {
00072 #ifdef WIN32
00073 DeleteCriticalSection(&critical_section);
00074 #else
00075 pthread_mutex_destroy(&handle);
00076 #endif
00077 }
00078
00080
00081
00082
00084
00085
00086 void CL_Mutex::lock()
00087 {
00088 #ifdef WIN32
00089 EnterCriticalSection(&critical_section);
00090 #else
00091 pthread_mutex_lock(&handle);
00092 #endif
00093 }
00094
00095 bool CL_Mutex::try_lock()
00096 {
00097 #ifdef WIN32
00098 BOOL result = TryEnterCriticalSection(&critical_section);
00099 return (result != FALSE);
00100 #else
00101 throw CL_Exception(TEXT("Congratulations, you just got the task of implementing CL_Mutex::try_lock() for unix!"));
00102 return false;
00103 #endif
00104 }
00105
00106 void CL_Mutex::unlock()
00107 {
00108 #ifdef WIN32
00109 LeaveCriticalSection(&critical_section);
00110 #else
00111 pthread_mutex_unlock(&handle);
00112 #endif
00113 }
00114
00116
00117
00118
00120
00121
00122 CL_MutexSection::CL_MutexSection(CL_Mutex *mutex, bool lock_mutex) : mutex(mutex), lock_count(0)
00123 {
00124 if (lock_mutex)
00125 lock();
00126 }
00127
00128 CL_MutexSection::~CL_MutexSection()
00129 {
00130 while (lock_count > 0)
00131 unlock();
00132 }
00133
00135
00136
00137 int CL_MutexSection::get_lock_count() const
00138 {
00139 return lock_count;
00140 }
00141
00143
00144
00145 void CL_MutexSection::lock()
00146 {
00147 if (mutex)
00148 mutex->lock();
00149 lock_count++;
00150 }
00151
00152 bool CL_MutexSection::try_lock()
00153 {
00154 if (mutex == 0 || mutex->try_lock())
00155 {
00156 lock_count++;
00157 return true;
00158 }
00159 return false;
00160 }
00161
00162 void CL_MutexSection::unlock()
00163 {
00164 if (lock_count <= 0)
00165 return;
00166
00167 if (mutex)
00168 mutex->unlock();
00169 lock_count--;
00170 }
00171
00173