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/. */
9 #include "nsThreadManager.h"
11 #include "nsThreadUtils.h"
17 static const uint32_t kDefaultThreadLifeTime
= 60; // in 60 seconds.
18 static const uint32_t kDelayPostTaskTime
= 20000; // in 20000 ms.
20 VRThread::VRThread(const nsCString
& aName
)
21 : mThread(nullptr), mLifeTime(kDefaultThreadLifeTime
), mStarted(false) {
25 VRThread::~VRThread() { Shutdown(); }
27 void VRThread::Start() {
29 nsresult rv
= NS_NewNamedThread(mName
, getter_AddRefs(mThread
));
33 MOZ_ASSERT(false, "Failed to create a vr thread.");
35 RefPtr
<Runnable
> runnable
=
36 NewRunnableMethod
<TimeStamp
>("gfx::VRThread::CheckLife", this,
37 &VRThread::CheckLife
, TimeStamp::Now());
38 // Post it to the main thread for tracking the lifetime.
39 nsCOMPtr
<nsIThread
> mainThread
;
40 rv
= NS_GetMainThread(getter_AddRefs(mainThread
));
42 NS_WARNING("VRThread::Start() could not get Main thread");
45 mainThread
->DelayedDispatch(runnable
.forget(), kDelayPostTaskTime
);
48 mLastActiveTime
= TimeStamp::Now();
51 void VRThread::Shutdown() {
53 if (nsThreadManager::get().IsNSThread()) {
57 "VRThread::Shutdown() may only be called from an XPCOM thread");
58 NS_DispatchToMainThread(NS_NewRunnableFunction(
59 "VRThread::Shutdown", [thread
= mThread
]() { thread
->Shutdown(); }));
66 const nsCOMPtr
<nsIThread
> VRThread::GetThread() const { return mThread
; }
68 void VRThread::PostTask(already_AddRefed
<Runnable
> aTask
) {
69 PostDelayedTask(std::move(aTask
), 0);
72 void VRThread::PostDelayedTask(already_AddRefed
<Runnable
> aTask
,
74 MOZ_ASSERT(mStarted
, "Must call Start() before posting tasks.");
76 mLastActiveTime
= TimeStamp::Now();
79 mThread
->Dispatch(std::move(aTask
), NS_DISPATCH_NORMAL
);
81 mThread
->DelayedDispatch(std::move(aTask
), aTime
);
85 void VRThread::CheckLife(TimeStamp aCheckTimestamp
) {
86 // VR system is going to shutdown.
92 const TimeDuration timeout
= TimeDuration::FromSeconds(mLifeTime
);
93 if ((aCheckTimestamp
- mLastActiveTime
) > timeout
) {
96 RefPtr
<Runnable
> runnable
=
97 NewRunnableMethod
<TimeStamp
>("gfx::VRThread::CheckLife", this,
98 &VRThread::CheckLife
, TimeStamp::Now());
99 // Post it to the main thread for tracking the lifetime.
100 nsCOMPtr
<nsIThread
> mainThread
;
101 nsresult rv
= NS_GetMainThread(getter_AddRefs(mainThread
));
103 NS_WARNING("VRThread::CheckLife() could not get Main thread");
106 mainThread
->DelayedDispatch(runnable
.forget(), kDelayPostTaskTime
);
110 void VRThread::SetLifeTime(uint32_t aLifeTime
) { mLifeTime
= aLifeTime
; }
112 uint32_t VRThread::GetLifeTime() { return mLifeTime
; }
114 bool VRThread::IsActive() { return !!mThread
; }
117 } // namespace mozilla