]> git.tdb.fi Git - libs/core.git/blob - source/mutex.h
0c2879e0cff6eb3301dd66c8c3c57faa3c1d0ba3
[libs/core.git] / source / mutex.h
1 /*
2 This file is part of libmspframework
3 Copyright © 2006 Mikko Rasa, Mikkosoft Productions
4 Distributed under the LGPL
5 */
6 #ifndef MSP_FRAMEWORK_MUTEX_H_
7 #define MSP_FRAMEWORK_MUTEX_H_
8
9 #include <pthread.h>
10 #include <msp/refcount.h>
11
12 namespace Msp {
13
14 class Mutex
15 {
16 public:
17         Mutex()       { pthread_mutex_init(&mutex, 0); }
18         int lock()    { return pthread_mutex_lock(&mutex); }
19         int trylock() { return pthread_mutex_trylock(&mutex); }
20         int unlock()  { return pthread_mutex_unlock(&mutex); }
21         ~Mutex()      { pthread_mutex_destroy(&mutex); }
22 private:
23         pthread_mutex_t mutex;
24
25         friend class Semaphore;
26 };
27
28 class MutexLock
29 {
30 public:
31         MutexLock(Mutex &m): mutex(m) { mutex.lock(); }
32         ~MutexLock()                  { mutex.unlock(); }
33 private:
34         Mutex &mutex;
35 };
36
37
38 template<typename T>
39 class MutexPtr: public RefCount
40 {
41 public:
42         MutexPtr(T *d, Mutex &m): mutex(m), data(d) { mutex.lock(); }
43         MutexPtr(const MutexPtr<T> &p): RefCount(p), mutex(p.mutex), data(p.data) { }
44         T &operator*() const { return *data; }
45         T *operator->() const { return data; }
46         void clear() { decref(); data=0; }
47         ~MutexPtr() { decref(); }
48 protected:
49         Mutex &mutex;
50         T     *data;
51
52         bool decref()
53         {
54                 if(!RefCount::decref())
55                 {
56                         mutex.unlock();
57                         return false;
58                 }
59                 return true;
60         }
61 };
62
63 }
64
65 #endif