]> git.tdb.fi Git - libs/core.git/blob - source/core/mutex.h
Assimilate exceptions and RefPtr from mspmisc
[libs/core.git] / source / core / mutex.h
1 /* $Id$
2
3 This file is part of libmspcore
4 Copyright © 2006 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7 #ifndef MSP_CORE_MUTEX_H_
8 #define MSP_CORE_MUTEX_H_
9
10 #include "refptr.h"
11 #include "types.h"
12
13 namespace Msp {
14
15 class Mutex
16 {
17 public:
18 #ifndef WIN32
19         Mutex()       { pthread_mutex_init(&mutex, 0); }
20         int lock()    { return pthread_mutex_lock(&mutex); }
21         int trylock() { return pthread_mutex_trylock(&mutex); }
22         int unlock()  { return pthread_mutex_unlock(&mutex); }
23         ~Mutex()      { pthread_mutex_destroy(&mutex); }
24 #else
25         Mutex()       { mutex=CreateMutex(0, false, 0); }
26         int lock()    { return WaitForSingleObject(mutex, INFINITE)==WAIT_OBJECT_0; }
27         int trylock() { return WaitForSingleObject(mutex, 0)==WAIT_OBJECT_0; }
28         int unlock()  { return !ReleaseMutex(mutex); }
29         ~Mutex()      { CloseHandle(mutex); }
30 #endif
31 private:
32         MutexHandle mutex;
33
34         friend class Semaphore;
35 };
36
37 /**
38 Locks the mutex for te lifetime of the object.
39 */
40 class MutexLock
41 {
42 public:
43         MutexLock(Mutex &m, bool l=true): mutex(m) { if(l) mutex.lock(); }
44         ~MutexLock() { mutex.unlock(); }
45
46         int lock() { return mutex.lock(); }
47 private:
48         Mutex &mutex;
49
50         MutexLock(const MutexLock &);
51         MutexLock &operator=(const MutexLock &);
52 };
53
54 /**
55 Protects a pointer with a mutex.  As long as the MutexPtr (or a copy of it)
56 exists, the mutex will stay locked.
57 */
58 template<typename T>
59 class MutexPtr
60 {
61 public:
62         MutexPtr(T *d, Mutex &m): mutex(new MutexLock(m)), data(d) { }
63
64         T &operator*() const { return *data; }
65         T *operator->() const { return data; }
66         void clear() { mutex=0; data=0; }
67 private:
68         RefPtr<MutexLock> mutex;
69         T *data;
70 };
71
72 /*template<typename T>
73 class MutexPtr: public RefCount
74 {
75 public:
76         MutexPtr(T *d, Mutex &m): mutex(m), data(d) { mutex.lock(); }
77         MutexPtr(const MutexPtr<T> &p): RefCount(p), mutex(p.mutex), data(p.data) { }
78         T &operator*() const { return *data; }
79         T *operator->() const { return data; }
80         void clear() { decref(); data=0; }
81         ~MutexPtr() { decref(); }
82 protected:
83         Mutex &mutex;
84         T     *data;
85
86         bool decref()
87         {
88                 if(!RefCount::decref())
89                 {
90                         mutex.unlock();
91                         return false;
92                 }
93                 return true;
94         }
95 };*/
96
97 }
98
99 #endif