]> git.tdb.fi Git - libs/core.git/blob - source/core/mutex.h
Throw out anything polling related - they will go to libmspio eventually
[libs/core.git] / source / core / mutex.h
1 /*
2 This file is part of libmspcore
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 <msp/refcount.h>
10 #include "types.h"
11
12 namespace Msp {
13
14 class Mutex
15 {
16 public:
17 #ifndef WIN32
18         Mutex()       { pthread_mutex_init(&mutex, 0); }
19         int lock()    { return pthread_mutex_lock(&mutex); }
20         int trylock() { return pthread_mutex_trylock(&mutex); }
21         int unlock()  { return pthread_mutex_unlock(&mutex); }
22         ~Mutex()      { pthread_mutex_destroy(&mutex); }
23 #else
24         Mutex()       { mutex=CreateMutex(0, false, 0); }
25         int lock()    { return WaitForSingleObject(mutex, INFINITE)==WAIT_OBJECT_0; }
26         int trylock() { return WaitForSingleObject(mutex, 0)==WAIT_OBJECT_0; }
27         int unlock()  { return !ReleaseMutex(mutex); }
28         ~Mutex()      { CloseHandle(mutex); }
29 #endif
30 private:
31         MutexHandle mutex;
32
33         friend class Semaphore;
34 };
35
36 class MutexLock
37 {
38 public:
39         MutexLock(Mutex &m): mutex(m) { mutex.lock(); }
40         ~MutexLock()                  { mutex.unlock(); }
41 private:
42         Mutex &mutex;
43
44         MutexLock(const MutexLock &);
45         MutexLock &operator=(const MutexLock &);
46 };
47
48
49 template<typename T>
50 class MutexPtr: public RefCount
51 {
52 public:
53         MutexPtr(T *d, Mutex &m): mutex(m), data(d) { mutex.lock(); }
54         MutexPtr(const MutexPtr<T> &p): RefCount(p), mutex(p.mutex), data(p.data) { }
55         T &operator*() const { return *data; }
56         T *operator->() const { return data; }
57         void clear() { decref(); data=0; }
58         ~MutexPtr() { decref(); }
59 protected:
60         Mutex &mutex;
61         T     *data;
62
63         bool decref()
64         {
65                 if(!RefCount::decref())
66                 {
67                         mutex.unlock();
68                         return false;
69                 }
70                 return true;
71         }
72 };
73
74 }
75
76 #endif