mutex.cpp
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 #include "mutex.h"
00020
00021 #include <stdlib.h>
00022
00023 #ifdef __UNIX__
00024 #include <pthread.h>
00025 #endif
00026 #ifdef __WIN32__
00027 #define _WINSOCKAPI_ // make windows.h happy about winsock.
00028 #include <windows.h>
00029 #endif
00030
00031 namespace basis {
00032
00033 mutex::mutex() { construct(); }
00034
00035 mutex::~mutex() { destruct(); }
00036
00037 void mutex::establish_lock() { lock(); }
00038
00039 void mutex::repeal_lock() { unlock(); }
00040
00041 void mutex::construct()
00042 {
00043 #ifdef __WIN32__
00044 c_os_mutex = (CRITICAL_SECTION *)malloc(sizeof(CRITICAL_SECTION));
00045 InitializeCriticalSection((LPCRITICAL_SECTION)c_os_mutex);
00046 #elif defined(__UNIX__)
00047 pthread_mutexattr_t attr;
00048 pthread_mutexattr_init(&attr);
00049 int ret = -1;
00050 #ifdef __APPLE__
00051 ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
00052 #else
00053 ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
00054 #endif
00055 if (ret != 0) {
00056
00057 }
00058 c_os_mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
00059 pthread_mutex_init((pthread_mutex_t *)c_os_mutex, &attr);
00060 pthread_mutexattr_destroy(&attr);
00061 #else
00062 #pragma error("no implementation of mutexes for this OS yet!")
00063 #endif
00064 }
00065
00066 void mutex::destruct()
00067 {
00068 defang();
00069 }
00070
00071 void mutex::defang()
00072 {
00073 if (!c_os_mutex) return;
00074 #ifdef __WIN32__
00075 DeleteCriticalSection((LPCRITICAL_SECTION)c_os_mutex);
00076 free(c_os_mutex);
00077 #elif defined(__UNIX__)
00078 pthread_mutex_destroy((pthread_mutex_t *)c_os_mutex);
00079 free(c_os_mutex);
00080 #else
00081 #pragma error("no implementation of mutexes for this OS yet!")
00082 #endif
00083 c_os_mutex = 0;
00084 }
00085
00086 void mutex::lock()
00087 {
00088 if (!c_os_mutex) return;
00089 #ifdef __WIN32__
00090 EnterCriticalSection((LPCRITICAL_SECTION)c_os_mutex);
00091 #elif defined(__UNIX__)
00092 pthread_mutex_lock((pthread_mutex_t *)c_os_mutex);
00093 #else
00094 #pragma error("no implementation of mutexes for this OS yet!")
00095 #endif
00096 }
00097
00098 void mutex::unlock()
00099 {
00100 if (!c_os_mutex) return;
00101 #ifdef __WIN32__
00102 LeaveCriticalSection((LPCRITICAL_SECTION)c_os_mutex);
00103 #elif defined(__UNIX__)
00104 pthread_mutex_unlock((pthread_mutex_t *)c_os_mutex);
00105 #else
00106 #pragma error("no implementation of mutexes for this OS yet!")
00107 #endif
00108 }
00109
00110 }
00111