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 
29 #include <pthread.h>
30 
31 
32 namespace MT
33 {
34 	class ScopedGuard;
35 
36 	//
37 	//
38 	//
39 	class Mutex
40 	{
41 		pthread_mutexattr_t mutexAttr;
42 		pthread_mutex_t mutex;
43 
44 	public:
45 
46 		MT_NOCOPYABLE(Mutex);
47 
48 		Mutex()
49 		{
50 			int res = pthread_mutexattr_init(&mutexAttr);
51 			MT_USED_IN_ASSERT(res);
52 			MT_ASSERT(res == 0, "pthread_mutexattr_init - failed");
53 
54 			res = pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE);
55 			MT_USED_IN_ASSERT(res);
56 			MT_ASSERT(res == 0, "pthread_mutexattr_settype - failed");
57 
58 			res = pthread_mutex_init(&mutex, &mutexAttr);
59 			MT_USED_IN_ASSERT(res);
60 			MT_ASSERT(res == 0, "pthread_mutex_init - failed");
61 		}
62 
63 		~Mutex()
64 		{
65 			int res = pthread_mutex_destroy(&mutex);
66 			MT_USED_IN_ASSERT(res);
67 			MT_ASSERT(res == 0, "pthread_mutex_destroy - failed");
68 
69 			res = pthread_mutexattr_destroy(&mutexAttr);
70 			MT_USED_IN_ASSERT(res);
71 			MT_ASSERT(res == 0, "pthread_mutexattr_destroy - failed");
72 		}
73 
74 		friend class MT::ScopedGuard;
75 
76 	private:
77 
78 		void Lock()
79 		{
80 			int res = pthread_mutex_lock(&mutex);
81 			MT_USED_IN_ASSERT(res);
82 			MT_ASSERT(res == 0, "pthread_mutex_lock - failed");
83 		}
84 		void Unlock()
85 		{
86 			int res = pthread_mutex_unlock(&mutex);
87 			MT_USED_IN_ASSERT(res);
88 			MT_ASSERT(res == 0, "pthread_mutex_unlock - failed");
89 		}
90 
91 	};
92 
93 
94 }
95 
96 
97 #endif