00001 00025 /* === S T A R T =========================================================== */ 00026 00027 #ifndef __ETL__MUTEX_PTHREADS_H_ 00028 #define __ETL__MUTEX_PTHREADS_H_ 00029 00030 /* === H E A D E R S ======================================================= */ 00031 00032 #define __USE_GNU 00033 00034 #include <pthread.h> 00035 00036 #ifdef HAVE_SCHED_H 00037 # include <sched.h> 00038 #endif 00039 00040 /* === M A C R O S ========================================================= */ 00041 00042 /* === C L A S S E S & S T R U C T S ======================================= */ 00043 00044 _ETL_BEGIN_NAMESPACE 00045 00046 class mutex 00047 { 00048 pthread_mutex_t mtx; 00049 pthread_t locker; 00050 int depth; 00051 public: 00052 00053 mutex() 00054 { 00055 pthread_mutexattr_t attr; 00056 pthread_mutexattr_init(&attr); 00057 //#ifdef PTHREAD_PRIO_INHERIT 00058 //pthread_mutexattr_setprioceiling(&attr,PTHREAD_PRIO_INHERIT); 00059 //#endif 00060 #ifdef PTHREAD_MUTEX_RECURSIVE 00061 pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE); 00062 #endif 00063 pthread_mutex_init(&mtx,&attr); 00064 pthread_mutexattr_destroy(&attr); 00065 locker=0; 00066 depth=0; 00067 } 00068 00069 ~mutex() 00070 { pthread_mutex_destroy(&mtx); } 00071 00072 00074 class lock 00075 { 00076 mutex *_mtx; 00077 public: 00078 lock(mutex &x):_mtx(&x) { _mtx->lock_mutex(); } 00079 ~lock() { _mtx->unlock_mutex(); } 00080 mutex &get() { return *_mtx; } 00081 }; 00082 00083 void lock_mutex(void) 00084 { 00085 if(!locker || locker!=pthread_self()) 00086 { 00087 pthread_mutex_lock(&mtx); 00088 locker=pthread_self(); 00089 depth=0; 00090 return; 00091 } 00092 depth++; 00093 } 00094 00095 bool try_lock_mutex(void) 00096 { return !(bool) pthread_mutex_trylock(&mtx); } 00097 00098 void unlock_mutex(void) 00099 { 00100 if(depth) 00101 { 00102 depth--; 00103 return; 00104 } 00105 pthread_mutex_unlock(&mtx); 00106 locker=0; 00107 } 00108 }; 00109 00110 _ETL_END_NAMESPACE 00111 00112 /* === E X T E R N S ======================================================= */ 00113 00114 /* === E N D =============================================================== */ 00115 00116 #endif