1 // Copyright (C)2004 Landmark Graphics Corporation
2 // Copyright (C)2005, 2006 Sun Microsystems, Inc.
3 // Copyright (C)2011, 2014 D. R. Commander
4 //
5 // This library is free software and may be redistributed and/or modified under
6 // the terms of the wxWindows Library License, Version 3.1 or (at your option)
7 // any later version.  The full license is in the LICENSE.txt file included
8 // with this distribution.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // wxWindows Library License for more details.
14 
15 #ifndef __MUTEX_H__
16 #define __MUTEX_H__
17 
18 #ifdef _WIN32
19 #include <windows.h>
20 #else
21 #include <pthread.h>
22 #include <semaphore.h>
23 #endif
24 
25 
26 namespace vglutil
27 {
28 	class Event
29 	{
30 		public:
31 
32 			Event(void);
33 			~Event(void);
34 			void wait(void);
35 			void signal(void);
36 			bool isLocked(void);
37 
38 		private:
39 
40 			#ifdef _WIN32
41 			HANDLE event;
42 			#else
43 			pthread_mutex_t mutex;
44 			pthread_cond_t cond;
45 			bool ready, deadYet;
46 			#endif
47 	};
48 
49 
50 	// Critical section (recursive mutex)
51 	class CriticalSection
52 	{
53 		public:
54 
55 			CriticalSection(void);
56 			~CriticalSection(void);
57 			void lock(bool errorCheck = true);
58 			void unlock(bool errorCheck = true);
59 
60 			class SafeLock
61 			{
62 				public:
63 
cs(cs_)64 					SafeLock(CriticalSection &cs_, bool errorCheck_ = true) : cs(cs_),
65 						errorCheck(errorCheck_)
66 					{
67 						cs.lock(errorCheck);
68 					}
~SafeLock()69 					~SafeLock() { cs.unlock(errorCheck); }
70 
71 				private:
72 
73 					CriticalSection &cs;
74 					bool errorCheck;
75 			};
76 
77 		protected:
78 
79 			#ifdef _WIN32
80 			HANDLE mutex;
81 			#else
82 			pthread_mutex_t mutex;
83 			#endif
84 	};
85 
86 
87 	class Semaphore
88 	{
89 		public:
90 
91 			Semaphore(long initialCount = 0);
92 			~Semaphore(void);
93 			void wait(void);
94 			bool tryWait();
95 			void post(void);
96 			long getValue(void);
97 
98 		private:
99 
100 			#ifdef _WIN32
101 			HANDLE sem;
102 			#elif defined(__APPLE__)
103 			char *semName;
104 			sem_t *sem;
105 			#else
106 			sem_t sem;
107 			#endif
108 	};
109 }
110 
111 #endif  // __MUTEX_H__
112