1 // The MIT License (MIT)
2 //
3 // 	Copyright (c) 2015 Sergey Makeev, Vadim Slyusarev
4 //
5 // 	Permission is hereby granted, free of charge, to any person obtaining a copy
6 // 	of this software and associated documentation files (the "Software"), to deal
7 // 	in the Software without restriction, including without limitation the rights
8 // 	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // 	copies of the Software, and to permit persons to whom the Software is
10 // 	furnished to do so, subject to the following conditions:
11 //
12 //  The above copyright notice and this permission notice shall be included in
13 // 	all copies or substantial portions of the Software.
14 //
15 // 	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // 	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // 	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // 	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // 	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // 	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 // 	THE SOFTWARE.
22 
23 #pragma once
24 
25 #ifndef __MT_MUTEX__
26 #define __MT_MUTEX__
27 
28 #include <pthread.h>
29 
30 
31 namespace MT
32 {
33 	class ScopedGuard;
34 
35 	//
36 	//
37 	//
38 	class Mutex
39 	{
40 		pthread_mutexattr_t mutexAttr;
41 		pthread_mutex_t mutex;
42 
43 	public:
44 
45 		MT_NOCOPYABLE(Mutex);
46 
Mutex()47 		Mutex()
48 		{
49 			int res = pthread_mutexattr_init(&mutexAttr);
50 			MT_USED_IN_ASSERT(res);
51 			MT_ASSERT(res == 0, "pthread_mutexattr_init - failed");
52 
53 			res = pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE);
54 			MT_USED_IN_ASSERT(res);
55 			MT_ASSERT(res == 0, "pthread_mutexattr_settype - failed");
56 
57 			res = pthread_mutex_init(&mutex, &mutexAttr);
58 			MT_USED_IN_ASSERT(res);
59 			MT_ASSERT(res == 0, "pthread_mutex_init - failed");
60 		}
61 
~Mutex()62 		~Mutex()
63 		{
64 			int res = pthread_mutex_destroy(&mutex);
65 			MT_USED_IN_ASSERT(res);
66 			MT_ASSERT(res == 0, "pthread_mutex_destroy - failed");
67 
68 			res = pthread_mutexattr_destroy(&mutexAttr);
69 			MT_USED_IN_ASSERT(res);
70 			MT_ASSERT(res == 0, "pthread_mutexattr_destroy - failed");
71 		}
72 
73 		friend class MT::ScopedGuard;
74 
75 	private:
76 
Lock()77 		void Lock()
78 		{
79 			int res = pthread_mutex_lock(&mutex);
80 			MT_USED_IN_ASSERT(res);
81 			MT_ASSERT(res == 0, "pthread_mutex_lock - failed");
82 		}
Unlock()83 		void Unlock()
84 		{
85 			int res = pthread_mutex_unlock(&mutex);
86 			MT_USED_IN_ASSERT(res);
87 			MT_ASSERT(res == 0, "pthread_mutex_unlock - failed");
88 		}
89 
90 	};
91 
92 
93 }
94 
95 
96 #endif
97