Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MikelSV Mutex
- class TLock{
- #ifdef WIN32
- CRITICAL_SECTION shared_mutex;
- #else
- pthread_mutex_t shared_mutex;
- #endif
- DWORD threadid;
- public:
- int lock; bool flock;
- TLock(){
- memset(this, 0, sizeof(*this));
- #ifdef WIN32
- #ifndef WINCE
- if(shared_mutex.LockCount>=0 && !shared_mutex.OwningThread) { InitializeCriticalSection(&shared_mutex); flock=1; }
- #else
- if(shared_mutex.LockCount==0 && !shared_mutex.hCrit){ InitializeCriticalSection(&shared_mutex); flock=1; }
- #endif
- #else
- pthread_mutex_init(&shared_mutex, NULL);
- #endif
- return ;
- }
- ~TLock(){
- if(lock) UnLock();
- #ifdef WIN32
- DeleteCriticalSection(&shared_mutex);
- #else
- pthread_mutex_destroy(&shared_mutex);
- #endif
- }
- bool IsLock(){
- DWORD thid=GetCurrentThreadId();
- if(lock && thid!=threadid){
- return 1;
- }
- return 0;
- }
- bool Lock(){
- #ifdef WIN32
- if(!flock){
- tlocklock.Lock();
- #ifndef WINCE
- if(shared_mutex.LockCount>=0 && !shared_mutex.OwningThread && !shared_mutex.LockSemaphore){
- InitializeCriticalSection(&shared_mutex); flock=1; lock=0; }
- #else
- if(shared_mutex.LockCount==0 && !shared_mutex.hCrit && !shared_mutex.LockSemaphore){ InitializeCriticalSection(&shared_mutex); flock=1; lock=0; }
- #endif
- tlocklock.UnLock();
- }
- #endif
- DWORD thid=GetCurrentThreadId();
- if(lock && thid==threadid){
- lock++; return 1;
- }
- #ifdef WIN32
- int llc=shared_mutex.LockCount;
- HANDLE t=shared_mutex.OwningThread;
- try{
- EnterCriticalSection(&shared_mutex);
- }catch(...){
- return 0;
- }
- if(lock || !shared_mutex.OwningThread){ // || t
- globalerror("GLOCK Lock!\r\n");
- }
- #else
- pthread_mutex_lock(&shared_mutex);
- if(lock){
- globalerror("GLOCK Lock!\r\n");
- }
- #endif
- lock=1; threadid=thid; return 1;
- }
- bool UnLock(){
- DWORD thid=GetCurrentThreadId();
- if(lock>1){
- if(thid!=threadid){
- globalerror("TLOCK UnLock thread id!\r\n"); return 0;
- }
- lock--; return 1;
- }
- #ifdef WIN32
- if(!lock || !shared_mutex.OwningThread){
- globalerror("GLOCK UnLock!\r\n");
- }
- lock=0; threadid=0;
- LeaveCriticalSection(&shared_mutex);
- #else
- if(!lock){
- globalerror("GLOCK UnLock!\r\n");
- }
- lock=0; threadid=0;
- pthread_mutex_unlock(&shared_mutex);
- #endif
- return 1;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement