#include "TMControlMutex.h"
#include <time.h>
#include <unistd.h>

extern pthread_mutex_t gMutex;

Bool_t TMControlMutex::instanceFlag = kFALSE;
TMControlMutex* TMControlMutex::single = NULL;
//___________________________________________________________________________________
TMControlMutex* TMControlMutex::Instance() {
 if(!instanceFlag) {
   instanceFlag = kTRUE;
   single = new TMControlMutex();
   return single;
 }
 else {
   return single;
 }
}
//___________________________________________________________________________________
TMControlMutex::TMControlMutex() :
  fMutexLocked(kFALSE)
{}
//___________________________________________________________________________________
TMControlMutex::~TMControlMutex() {
  instanceFlag=kFALSE;
}
//___________________________________________________________________________________
void TMControlMutex::ITakeLock() {
  //  if (fMutexLocked) printf("ITakeLock: mutex already locked by %ld (override)\n",fThreadLocked);
  fMutexLocked = kTRUE;
  fThreadLocked = pthread_self();
  //  printf("LOCK %ld\n",fThreadLocked);
}
//___________________________________________________________________________________
void TMControlMutex::IReleaseLock() {
  //  if (!fMutexLocked) printf("IReleaseLock: mutex not locked?\n");
  fMutexLocked = kFALSE;
  //  printf("UN-LOCK %ld\n",fThreadLocked);
}
//___________________________________________________________________________________
Bool_t TMControlMutex::DoIHaveLock() {
  if (!fMutexLocked) return kFALSE;
  if (pthread_equal(pthread_self(),fThreadLocked)) return kTRUE;
  //  else printf("DoIHaveLock: mutex locked by %ld\n",fThreadLocked);
  return kFALSE;
}
//___________________________________________________________________________________
Bool_t TMControlMutex::Lock() {
  // returns true if mutex needed to be locked
  if (fMutexLocked) {
    if (pthread_equal(pthread_self(),fThreadLocked)) {
      return kFALSE;
    }
  }
  pthread_mutex_lock(&gMutex);
  fThreadLocked = pthread_self();
  fMutexLocked = kTRUE;
  //  printf("locking %ld\n",pthread_self());
  return kTRUE;
}
//___________________________________________________________________________________
void TMControlMutex::UnLock() {
  pthread_mutex_unlock(&gMutex);
  //  printf("UNlocki %ld\n",pthread_self());
  fMutexLocked = kFALSE;
}
//___________________________________________________________________________________
void TMControlMutex::ResetMutex() {
  pthread_mutex_destroy(&gMutex);
  pthread_mutex_init(&gMutex,NULL);
  fMutexLocked = kFALSE;
  fThreadLocked = 999999999;
}
