Jamoma API  0.6.0.a19
CAGuard.cpp
1 /* Copyright © 2007 Apple Inc. All Rights Reserved.
2 
3  Disclaimer: IMPORTANT: This Apple software is supplied to you by
4  Apple Inc. ("Apple") in consideration of your agreement to the
5  following terms, and your use, installation, modification or
6  redistribution of this Apple software constitutes acceptance of these
7  terms. If you do not agree with these terms, please do not use,
8  install, modify or redistribute this Apple software.
9 
10  In consideration of your agreement to abide by the following terms, and
11  subject to these terms, Apple grants you a personal, non-exclusive
12  license, under Apple's copyrights in this original Apple software (the
13  "Apple Software"), to use, reproduce, modify and redistribute the Apple
14  Software, with or without modifications, in source and/or binary forms;
15  provided that if you redistribute the Apple Software in its entirety and
16  without modifications, you must retain this notice and the following
17  text and disclaimers in all such redistributions of the Apple Software.
18  Neither the name, trademarks, service marks or logos of Apple Inc.
19  may be used to endorse or promote products derived from the Apple
20  Software without specific prior written permission from Apple. Except
21  as expressly stated in this notice, no other rights or licenses, express
22  or implied, are granted by Apple herein, including but not limited to
23  any patent rights that may be infringed by your derivative works or by
24  other works in which the Apple Software may be incorporated.
25 
26  The Apple Software is provided by Apple on an "AS IS" basis. APPLE
27  MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
28  THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
29  FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
30  OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
31 
32  IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
33  OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
36  MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
37  AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
38  STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
39  POSSIBILITY OF SUCH DAMAGE.
40 */
41 //==================================================================================================
42 // Includes
43 //==================================================================================================
44 
45 // Self Include
46 #include "CAGuard.h"
47 
48 #if TARGET_OS_MAC
49  #include <errno.h>
50 #endif
51 
52 // PublicUtility Inludes
53 #include "CADebugMacros.h"
54 #include "CAException.h"
55 #include "CAHostTimeBase.h"
56 
57 //==================================================================================================
58 // Logging
59 //==================================================================================================
60 
61 #if CoreAudio_Debug
62 // #define Log_Ownership 1
63 // #define Log_WaitOwnership 1
64 // #define Log_TimedWaits 1
65 // #define Log_Latency 1
66 // #define Log_Errors 1
67 #endif
68 
69 //#warning Need a try-based Locker too
70 //==================================================================================================
71 // CAGuard
72 //==================================================================================================
73 
74 CAGuard::CAGuard(const char* inName)
75 :
76  CAMutex(inName)
77 #if Log_Average_Latency
78  ,mAverageLatencyAccumulator(0.0),
79  mAverageLatencyCount(0)
80 #endif
81 {
82 #if TARGET_OS_MAC
83  OSStatus theError = pthread_cond_init(&mCondVar, NULL);
84  ThrowIf(theError != 0, CAException(theError), "CAGuard::CAGuard: Could not init the cond var");
85 #elif TARGET_OS_WIN32
86  mEvent = CreateEvent(NULL, true, false, NULL);
87  ThrowIfNULL(mEvent, CAException(GetLastError()), "CAGuard::CAGuard: Could not create the event");
88 #endif
89 }
90 
91 CAGuard::~CAGuard()
92 {
93 #if TARGET_OS_MAC
94  pthread_cond_destroy(&mCondVar);
95 #elif TARGET_OS_WIN32
96  if(mEvent != NULL)
97  {
98  CloseHandle(mEvent);
99  }
100 #endif
101 }
102 
103 void CAGuard::Wait()
104 {
105 #if TARGET_OS_MAC
106  ThrowIf(!pthread_equal(pthread_self(), mOwner), CAException(1), "CAGuard::Wait: A thread has to have locked a guard before it can wait");
107 
108  mOwner = 0;
109 
110  #if Log_WaitOwnership
111  DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::Wait: thread %p is waiting on %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner);
112  #endif
113 
114  OSStatus theError = pthread_cond_wait(&mCondVar, &mMutex);
115  ThrowIf(theError != 0, CAException(theError), "CAGuard::Wait: Could not wait for a signal");
116  mOwner = pthread_self();
117 
118  #if Log_WaitOwnership
119  DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::Wait: thread %p waited on %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner);
120  #endif
121 #elif TARGET_OS_WIN32
122  ThrowIf(GetCurrentThreadId() != mOwner, CAException(1), "CAGuard::Wait: A thread has to have locked a guard before it can wait");
123 
124  mOwner = 0;
125 
126  #if Log_WaitOwnership
127  DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::Wait: thread %lu is waiting on %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner);
128  #endif
129 
130  ReleaseMutex(mMutex);
131  HANDLE theHandles[] = { mMutex, mEvent };
132  OSStatus theError = WaitForMultipleObjects(2, theHandles, true, INFINITE);
133  ThrowIfError(theError, CAException(GetLastError()), "CAGuard::Wait: Could not wait for the signal");
134  mOwner = GetCurrentThreadId();
135  ResetEvent(mEvent);
136 
137  #if Log_WaitOwnership
138  DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::Wait: thread %lu waited on %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner);
139  #endif
140 #endif
141 }
142 
143 bool CAGuard::WaitFor(UInt64 inNanos)
144 {
145  bool theAnswer = false;
146 
147 #if TARGET_OS_MAC
148  ThrowIf(!pthread_equal(pthread_self(), mOwner), CAException(1), "CAGuard::WaitFor: A thread has to have locked a guard be for it can wait");
149 
150  #if Log_TimedWaits
151  DebugMessageN1("CAGuard::WaitFor: waiting %.0f", (Float64)inNanos);
152  #endif
153 
154  struct timespec theTimeSpec;
155  static const UInt64 kNanosPerSecond = 1000000000ULL;
156  if(inNanos >= kNanosPerSecond)
157  {
158  theTimeSpec.tv_sec = static_cast<UInt32>(inNanos / kNanosPerSecond);
159  theTimeSpec.tv_nsec = static_cast<UInt32>(inNanos % kNanosPerSecond);
160  }
161  else
162  {
163  theTimeSpec.tv_sec = 0;
164  theTimeSpec.tv_nsec = static_cast<UInt32>(inNanos);
165  }
166 
167  #if Log_TimedWaits || Log_Latency || Log_Average_Latency
168  UInt64 theStartNanos = CAHostTimeBase::GetCurrentTimeInNanos();
169  #endif
170 
171  mOwner = 0;
172 
173  #if Log_WaitOwnership
174  DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::WaitFor: thread %p is waiting on %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner);
175  #endif
176 
177  OSStatus theError = pthread_cond_timedwait_relative_np(&mCondVar, &mMutex, &theTimeSpec);
178  ThrowIf((theError != 0) && (theError != ETIMEDOUT), CAException(theError), "CAGuard::WaitFor: Wait got an error");
179  mOwner = pthread_self();
180 
181  #if Log_TimedWaits || Log_Latency || Log_Average_Latency
182  UInt64 theEndNanos = CAHostTimeBase::GetCurrentTimeInNanos();
183  #endif
184 
185  #if Log_TimedWaits
186  DebugMessageN1("CAGuard::WaitFor: waited %.0f", (Float64)(theEndNanos - theStartNanos));
187  #endif
188 
189  #if Log_Latency
190  DebugMessageN1("CAGuard::WaitFor: latency %.0f", (Float64)((theEndNanos - theStartNanos) - inNanos));
191  #endif
192 
193  #if Log_Average_Latency
194  ++mAverageLatencyCount;
195  mAverageLatencyAccumulator += (theEndNanos - theStartNanos) - inNanos;
196  if(mAverageLatencyCount >= 50)
197  {
198  DebugMessageN2("CAGuard::WaitFor: average latency %.3f ns over %ld waits", mAverageLatencyAccumulator / mAverageLatencyCount, mAverageLatencyCount);
199  mAverageLatencyCount = 0;
200  mAverageLatencyAccumulator = 0.0;
201  }
202  #endif
203 
204  #if Log_WaitOwnership
205  DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::WaitFor: thread %p waited on %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner);
206  #endif
207 
208  theAnswer = theError == ETIMEDOUT;
209 #elif TARGET_OS_WIN32
210  ThrowIf(GetCurrentThreadId() != mOwner, CAException(1), "CAGuard::WaitFor: A thread has to have locked a guard be for it can wait");
211 
212  #if Log_TimedWaits
213  DebugMessageN1("CAGuard::WaitFor: waiting %.0f", (Float64)inNanos);
214  #endif
215 
216  // the time out is specified in milliseconds(!)
217  UInt32 theWaitTime = static_cast<UInt32>(inNanos / 1000000ULL);
218 
219  #if Log_TimedWaits || Log_Latency || Log_Average_Latency
220  UInt64 theStartNanos = CAHostTimeBase::GetCurrentTimeInNanos();
221  #endif
222 
223  mOwner = 0;
224 
225  #if Log_WaitOwnership
226  DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::WaitFor: thread %lu is waiting on %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner);
227  #endif
228 
229  ReleaseMutex(mMutex);
230  HANDLE theHandles[] = { mMutex, mEvent };
231  OSStatus theError = WaitForMultipleObjects(2, theHandles, true, theWaitTime);
232  ThrowIf((theError != WAIT_OBJECT_0) && (theError != WAIT_TIMEOUT), CAException(GetLastError()), "CAGuard::WaitFor: Wait got an error");
233  mOwner = GetCurrentThreadId();
234  ResetEvent(mEvent);
235 
236  #if Log_TimedWaits || Log_Latency || Log_Average_Latency
237  UInt64 theEndNanos = CAHostTimeBase::GetCurrentTimeInNanos();
238  #endif
239 
240  #if Log_TimedWaits
241  DebugMessageN1("CAGuard::WaitFor: waited %.0f", (Float64)(theEndNanos - theStartNanos));
242  #endif
243 
244  #if Log_Latency
245  DebugMessageN1("CAGuard::WaitFor: latency %.0f", (Float64)((theEndNanos - theStartNanos) - inNanos));
246  #endif
247 
248  #if Log_Average_Latency
249  ++mAverageLatencyCount;
250  mAverageLatencyAccumulator += (theEndNanos - theStartNanos) - inNanos;
251  if(mAverageLatencyCount >= 50)
252  {
253  DebugMessageN2("CAGuard::WaitFor: average latency %.3f ns over %ld waits", mAverageLatencyAccumulator / mAverageLatencyCount, mAverageLatencyCount);
254  mAverageLatencyCount = 0;
255  mAverageLatencyAccumulator = 0.0;
256  }
257  #endif
258 
259  #if Log_WaitOwnership
260  DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::WaitFor: thread %lu waited on %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner);
261  #endif
262 
263  theAnswer = theError == WAIT_TIMEOUT;
264 #endif
265 
266  return theAnswer;
267 }
268 
269 bool CAGuard::WaitUntil(UInt64 inNanos)
270 {
271  bool theAnswer = false;
272  UInt64 theCurrentNanos = CAHostTimeBase::GetCurrentTimeInNanos();
273 
274 #if Log_TimedWaits
275  DebugMessageN2("CAGuard::WaitUntil: now: %.0f, requested: %.0f", (double)theCurrentNanos, (double)inNanos);
276 #endif
277 
278  if(inNanos > theCurrentNanos)
279  {
280 #if Log_Errors
281  if((inNanos - theCurrentNanos) > 1000000000ULL)
282  {
283  DebugMessage("CAGuard::WaitUntil: about to wait for more than a second");
284  }
285 #endif
286  theAnswer = WaitFor(inNanos - theCurrentNanos);
287  }
288  else
289  {
290 #if Log_Errors
291  DebugMessageN2("CAGuard::WaitUntil: Time has expired before waiting, now: %.0f, requested: %.0f", (double)theCurrentNanos, (double)inNanos);
292 #endif
293  theAnswer = true;
294  }
295 
296  return theAnswer;
297 }
298 
299 void CAGuard::Notify()
300 {
301 #if TARGET_OS_MAC
302  #if Log_WaitOwnership
303  DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::Notify: thread %p is notifying %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner);
304  #endif
305 
306  OSStatus theError = pthread_cond_signal(&mCondVar);
307  ThrowIf(theError != 0, CAException(theError), "CAGuard::Notify: failed");
308 #elif TARGET_OS_WIN32
309  #if Log_WaitOwnership
310  DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::Notify: thread %lu is notifying %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner);
311  #endif
312 
313  SetEvent(mEvent);
314 #endif
315 }
316 
317 void CAGuard::NotifyAll()
318 {
319 #if TARGET_OS_MAC
320  #if Log_WaitOwnership
321  DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::NotifyAll: thread %p is notifying %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner);
322  #endif
323 
324  OSStatus theError = pthread_cond_broadcast(&mCondVar);
325  ThrowIf(theError != 0, CAException(theError), "CAGuard::NotifyAll: failed");
326 #elif TARGET_OS_WIN32
327  #if Log_WaitOwnership
328  DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::NotifyAll: thread %lu is notifying %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner);
329  #endif
330 
331  SetEvent(mEvent);
332 #endif
333 }