1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
#include "stdafx.h"
#include "Lock.h"
namespace util {
#ifdef WINDOWS
// Default spin count. This is what the heap manager uses internally according to MSDN. We
// typically have fairly short critical sections here, so this should work well for us as well.
static const DWORD spinCount = 4000;
Lock::Lock() {
InitializeCriticalSectionAndSpinCount(&cs, spinCount);
}
Lock::~Lock() {
DeleteCriticalSection(&cs);
}
Lock::L::L(Lock &l) : l(&l) {
EnterCriticalSection(&l.cs);
}
Lock::L::L(Lock *l) : l(l) {
if (l)
EnterCriticalSection(&l->cs);
}
Lock::L::~L() {
if (l)
LeaveCriticalSection(&l->cs);
}
void Lock::lock() {
EnterCriticalSection(&cs);
}
void Lock::unlock() {
LeaveCriticalSection(&cs);
}
#endif
#ifdef POSIX
Lock::Lock() {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&cs, &attr);
pthread_mutexattr_destroy(&attr);
}
Lock::~Lock() {
pthread_mutex_destroy(&cs);
}
Lock::L::L(Lock &l) : l(&l) {
// According to the man pages, we do not need to consider EINTR from locking a mutex.
pthread_mutex_lock(&l.cs);
}
Lock::L::L(Lock *l) : l(l) {
// According to the man pages, we do not need to consider EINTR from locking a mutex.
if (l)
pthread_mutex_lock(&l->cs);
}
Lock::L::~L() {
if (l)
pthread_mutex_unlock(&l->cs);
}
void Lock::lock() {
pthread_mutex_lock(&cs);
}
void Lock::unlock() {
pthread_mutex_unlock(&cs);
}
#endif
}
|