1 //===-- PThreadMutex.h ------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Created by Greg Clayton on 6/16/07.
12 //===----------------------------------------------------------------------===//
14 #ifndef __PThreadMutex_h__
15 #define __PThreadMutex_h__
21 //#define DEBUG_PTHREAD_MUTEX_DEADLOCKS 1
23 #if defined(DEBUG_PTHREAD_MUTEX_DEADLOCKS)
24 #define PTHREAD_MUTEX_LOCKER(var, mutex) \
25 PThreadMutex::Locker var(mutex, __FUNCTION__, __FILE__, __LINE__)
28 #define PTHREAD_MUTEX_LOCKER(var, mutex) PThreadMutex::Locker var(mutex)
35 #if defined(DEBUG_PTHREAD_MUTEX_DEADLOCKS)
37 Locker(PThreadMutex &m, const char *function, const char *file, int line);
38 Locker(PThreadMutex *m, const char *function, const char *file, int line);
39 Locker(pthread_mutex_t *mutex, const char *function, const char *file,
46 Locker(PThreadMutex &m) : m_pMutex(m.Mutex()) { Lock(); }
48 Locker(PThreadMutex *m) : m_pMutex(m ? m->Mutex() : NULL) { Lock(); }
50 Locker(pthread_mutex_t *mutex) : m_pMutex(mutex) { Lock(); }
54 ::pthread_mutex_lock(m_pMutex);
59 ::pthread_mutex_unlock(m_pMutex);
62 ~Locker() { Unlock(); }
66 // unlock any the current mutex and lock the new one if it is valid
67 void Reset(pthread_mutex_t *pMutex = NULL) {
72 pthread_mutex_t *m_pMutex;
73 #if defined(DEBUG_PTHREAD_MUTEX_DEADLOCKS)
74 const char *m_function;
83 err = ::pthread_mutex_init(&m_mutex, NULL);
87 PThreadMutex(int type) {
89 ::pthread_mutexattr_t attr;
90 err = ::pthread_mutexattr_init(&attr);
92 err = ::pthread_mutexattr_settype(&attr, type);
94 err = ::pthread_mutex_init(&m_mutex, &attr);
96 err = ::pthread_mutexattr_destroy(&attr);
102 err = ::pthread_mutex_destroy(&m_mutex);
106 ::pthread_mutex_destroy(&m_mutex);
110 pthread_mutex_t *Mutex() { return &m_mutex; }
112 int Lock() { return ::pthread_mutex_lock(&m_mutex); }
114 int Unlock() { return ::pthread_mutex_unlock(&m_mutex); }
117 pthread_mutex_t m_mutex;