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_EVENT__
26 #define __MT_EVENT__
27 
28 
29 #include <sys/time.h>
30 #include <sched.h>
31 #include <errno.h>
32 
33 
34 namespace MT
35 {
36 	//
37 	//
38 	//
39 	class Event
40 	{
41 		static const int NOT_SIGNALED = 0;
42 		static const int SIGNALED = 1;
43 
44 		uint32 numOfWaitingThreads;
45 
46 		pthread_mutex_t	mutex;
47 		pthread_cond_t	condition;
48 		AtomicInt32 val;
49 		EventReset::Type resetType;
50 		bool isInitialized;
51 
52 	private:
53 
54 		Event(const Event&) {}
55 		void operator=(const Event&) {}
56 
57 		void AutoResetIfNeed()
58 		{
59 			if (resetType == EventReset::MANUAL)
60 			{
61 				return;
62 			}
63 			Reset();
64 		}
65 
66 	public:
67 
68 		Event()
69 			: numOfWaitingThreads(0)
70 			, isInitialized(false)
71 		{
72 		}
73 
74 		Event(EventReset::Type resetType, bool initialState)
75 			: numOfWaitingThreads(0)
76 			, isInitialized(false)
77 		{
78 			Create(resetType, initialState);
79 		}
80 
81 		~Event()
82 		{
83 			if (isInitialized)
84 			{
85 				pthread_cond_destroy( &condition );
86 				pthread_mutex_destroy( &mutex );
87 			}
88 		}
89 
90 		void Create(EventReset::Type _resetType, bool initialState)
91 		{
92 			MT_ASSERT (!isInitialized, "Event already initialized");
93 
94 			resetType = _resetType;
95 
96 			pthread_mutex_init( &mutex, nullptr );
97 			pthread_cond_init( &condition, nullptr );
98 			val.Store(initialState ? SIGNALED : NOT_SIGNALED);
99 
100 			isInitialized = true;
101 			numOfWaitingThreads = 0;
102 		}
103 
104 		void Signal()
105 		{
106 			MT_ASSERT (isInitialized, "Event not initialized");
107 
108 			pthread_mutex_lock( &mutex );
109 
110 			val.Store(SIGNALED);
111 
112 			if (numOfWaitingThreads)
113 			{
114 				if (resetType == EventReset::MANUAL)
115 				{
116 					pthread_cond_broadcast( &condition );
117 				} else
118 				{
119 					pthread_cond_signal( &condition );
120 				}
121 			}
122 
123 			pthread_mutex_unlock( &mutex );
124 		}
125 
126 		void Reset()
127 		{
128 			MT_ASSERT (isInitialized, "Event not initialized");
129 			val.Store(NOT_SIGNALED);
130 		}
131 
132 		bool Wait(uint32 milliseconds)
133 		{
134 			MT_ASSERT (isInitialized, "Event not initialized");
135 
136 			pthread_mutex_lock( &mutex );
137 
138 			// early exit if event already signaled
139 			if ( val.Load() != NOT_SIGNALED )
140 			{
141 				AutoResetIfNeed();
142 				pthread_mutex_unlock( &mutex );
143 				return true;
144 			}
145 
146 			numOfWaitingThreads++;
147 
148 			//convert milliseconds to posix time
149 			struct timeval tv;
150 			gettimeofday( &tv, nullptr );
151 			struct timespec tm;
152 			tm.tv_sec = tv.tv_sec + milliseconds / 1000;
153 			uint64 nanosec = (uint64)tv.tv_usec * 1000 + (uint64)milliseconds * 1000000;
154 			if (nanosec >= 1000000000)
155 			{
156 				tm.tv_sec += (long)(nanosec / 1000000000);
157 				nanosec = nanosec % 1000000000;
158 			}
159 			tm.tv_nsec = (long)nanosec;
160 
161 			int ret = 0;
162 			while(true)
163 			{
164 				ret = pthread_cond_timedwait( &condition, &mutex, &tm );
165 
166 				MT_ASSERT(ret == 0 || ret == ETIMEDOUT || ret == EINTR, "Unexpected return value");
167 
168 				if (ret != EINTR)
169 				{
170 					break;
171 				}
172 			}
173 
174 			numOfWaitingThreads--;
175 
176 			AutoResetIfNeed();
177 
178 			pthread_mutex_unlock( &mutex );
179 
180 			//return true if val in SIGNALED state instead of ret == 0 ?
181 			return ret == 0;
182 		}
183 
184 	};
185 
186 }
187 
188 
189 #endif