1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "mozilla/mscom/SpinEvent.h"
8 
9 #include "mozilla/ArrayUtils.h"
10 #include "mozilla/Assertions.h"
11 #include "mozilla/TimeStamp.h"
12 #include "nsServiceManagerUtils.h"
13 #include "nsString.h"
14 #include "nsSystemInfo.h"
15 
16 namespace mozilla {
17 namespace mscom {
18 
19 static const TimeDuration kMaxSpinTime = TimeDuration::FromMilliseconds(30);
20 bool SpinEvent::sIsMulticore = false;
21 
22 /* static */
InitStatics()23 bool SpinEvent::InitStatics() {
24   SYSTEM_INFO sysInfo;
25   ::GetSystemInfo(&sysInfo);
26   sIsMulticore = sysInfo.dwNumberOfProcessors > 1;
27   return true;
28 }
29 
SpinEvent()30 SpinEvent::SpinEvent() : mDone(false) {
31   static const bool gotStatics = InitStatics();
32   MOZ_ALWAYS_TRUE(gotStatics);
33 
34   mDoneEvent.own(::CreateEventW(nullptr, FALSE, FALSE, nullptr));
35   MOZ_ASSERT(mDoneEvent);
36 }
37 
Wait(HANDLE aTargetThread)38 bool SpinEvent::Wait(HANDLE aTargetThread) {
39   MOZ_ASSERT(aTargetThread);
40   if (!aTargetThread) {
41     return false;
42   }
43 
44   if (sIsMulticore) {
45     // Bug 1311834: Spinning allows for faster response than waiting on an
46     // event, as events are constrained by the system's timer resolution.
47     // Bug 1429665: However, we only want to spin for a very short time. If
48     // we're waiting for a while, we don't want to be burning CPU for the
49     // entire time. At that point, a few extra ms isn't going to make much
50     // difference to perceived responsiveness.
51     TimeStamp start(TimeStamp::Now());
52     while (!mDone) {
53       TimeDuration elapsed(TimeStamp::Now() - start);
54       if (elapsed >= kMaxSpinTime) {
55         break;
56       }
57       YieldProcessor();
58     }
59     if (mDone) {
60       return true;
61     }
62   }
63 
64   MOZ_ASSERT(mDoneEvent);
65   HANDLE handles[] = {mDoneEvent, aTargetThread};
66   DWORD waitResult = ::WaitForMultipleObjects(mozilla::ArrayLength(handles),
67                                               handles, FALSE, INFINITE);
68   return waitResult == WAIT_OBJECT_0;
69 }
70 
Signal()71 void SpinEvent::Signal() {
72   ::SetEvent(mDoneEvent);
73   mDone = true;
74 }
75 
76 }  // namespace mscom
77 }  // namespace mozilla
78