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