]> git.tdb.fi Git - libs/core.git/blob - source/mutex.h
Native threads for Win32
[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 <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
45
46 template<typename T>
47 class MutexPtr: public RefCount
48 {
49 public:
50         MutexPtr(T *d, Mutex &m): mutex(m), data(d) { mutex.lock(); }
51         MutexPtr(const MutexPtr<T> &p): RefCount(p), mutex(p.mutex), data(p.data) { }
52         T &operator*() const { return *data; }
53         T *operator->() const { return data; }
54         void clear() { decref(); data=0; }
55         ~MutexPtr() { decref(); }
56 protected:
57         Mutex &mutex;
58         T     *data;
59
60         bool decref()
61         {
62                 if(!RefCount::decref())
63                 {
64                         mutex.unlock();
65                         return false;
66                 }
67                 return true;
68         }
69 };
70
71 }
72
73 #endif