blob: 855a692d9e96a2dab5a7273cb693bc7af1d4774f (
plain)
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
83
84
85
86
87
88
89
90
91
92
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef __MUTEX_H
#define __MUTEX_H
#include <pthread.h>
#include "include/assert.h"
class Mutex {
private:
pthread_mutex_t _m;
int nlock;
bool recursive;
// don't allow copying.
void operator=(Mutex &M) {}
Mutex( const Mutex &M ) {}
public:
Mutex(bool r = true) : nlock(0), recursive(r) {
if (recursive) {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&_m,&attr);
pthread_mutexattr_destroy(&attr);
} else {
pthread_mutex_init(&_m,NULL);
}
}
~Mutex() {
assert(nlock == 0);
pthread_mutex_destroy(&_m);
}
bool is_locked() {
return (nlock > 0);
}
bool TryLock() {
int r = pthread_mutex_trylock(&_m);
if (r == 0) {
nlock++;
assert(nlock == 1 || recursive);
}
return r == 0;
}
void Lock() {
int r = pthread_mutex_lock(&_m);
assert(r == 0);
nlock++;
assert(nlock == 1 || recursive);
}
void Unlock() {
assert(nlock > 0);
--nlock;
int r = pthread_mutex_unlock(&_m);
assert(r == 0);
}
friend class Cond;
public:
class Locker {
Mutex &mutex;
public:
Locker(Mutex& m) : mutex(m) {
mutex.Lock();
}
~Locker() {
mutex.Unlock();
}
};
};
#endif
|