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/. */
7 #ifndef nsThreadSyncDispatch_h_
8 #define nsThreadSyncDispatch_h_
10 #include "mozilla/Atomics.h"
11 #include "mozilla/DebugOnly.h"
12 #include "mozilla/SpinEventLoopUntil.h"
14 #include "nsThreadUtils.h"
15 #include "LeakRefPtr.h"
17 class nsThreadSyncDispatch
: public mozilla::Runnable
{
19 nsThreadSyncDispatch(already_AddRefed
<nsIEventTarget
> aOrigin
,
20 already_AddRefed
<nsIRunnable
>&& aTask
)
21 : Runnable("nsThreadSyncDispatch"),
23 mSyncTask(std::move(aTask
)),
27 // This is an atomic acquire on the origin thread.
31 void SpinEventLoopUntilComplete(const nsACString
& aVeryGoodReasonToDoThis
) {
32 mozilla::SpinEventLoopUntil(aVeryGoodReasonToDoThis
,
33 [&]() -> bool { return !IsPending(); });
37 NS_IMETHOD
Run() override
{
38 if (nsCOMPtr
<nsIRunnable
> task
= mSyncTask
.take()) {
39 MOZ_ASSERT(!mSyncTask
);
41 mozilla::DebugOnly
<nsresult
> result
= task
->Run();
42 MOZ_ASSERT(NS_SUCCEEDED(result
), "task in sync dispatch should not fail");
44 // We must release the task here to ensure that when the original
45 // thread is unblocked, this task has been released.
48 // This is an atomic release on the target thread.
51 // unblock the origin thread
52 mOrigin
->Dispatch(this, NS_DISPATCH_IGNORE_BLOCK_DISPATCH
);
58 nsCOMPtr
<nsIEventTarget
> mOrigin
;
59 // The task is leaked by default when Run() is not called, because
60 // otherwise we may release it in an incorrect thread.
61 mozilla::LeakRefPtr
<nsIRunnable
> mSyncTask
;
62 mozilla::Atomic
<bool, mozilla::ReleaseAcquire
> mIsPending
;
65 #endif // nsThreadSyncDispatch_h_