ThreadUtils.cpp (2547B)
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 file, 5 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #include "mozilla/dom/quota/ThreadUtils.h" 8 9 #include "mozilla/dom/quota/QuotaCommon.h" 10 #include "mozilla/dom/quota/ResultExtensions.h" 11 #include "nsIThreadInternal.h" 12 #include "nsThreadPool.h" 13 #include "nsThreadUtils.h" 14 #include "prinrval.h" 15 #include "prthread.h" 16 17 namespace mozilla::dom::quota { 18 19 namespace { 20 21 class RunAfterProcessingCurrentEventHelper final : public nsIThreadObserver { 22 public: 23 nsresult Init(std::function<void()>&& aCallback); 24 25 NS_DECL_ISUPPORTS 26 NS_DECL_NSITHREADOBSERVER 27 28 private: 29 ~RunAfterProcessingCurrentEventHelper() = default; 30 31 std::function<void()> mCallback; 32 }; 33 34 } // namespace 35 36 nsresult RunAfterProcessingCurrentEventHelper::Init( 37 std::function<void()>&& aCallback) { 38 nsCOMPtr<nsIThreadInternal> thread = do_QueryInterface(NS_GetCurrentThread()); 39 MOZ_ASSERT(thread); 40 41 QM_TRY(MOZ_TO_RESULT(thread->AddObserver(this))); 42 43 mCallback = std::move(aCallback); 44 45 return NS_OK; 46 } 47 48 NS_IMPL_ISUPPORTS(RunAfterProcessingCurrentEventHelper, nsIThreadObserver) 49 50 NS_IMETHODIMP 51 RunAfterProcessingCurrentEventHelper::OnDispatchedEvent() { 52 MOZ_CRASH("Should never be called!"); 53 } 54 55 NS_IMETHODIMP 56 RunAfterProcessingCurrentEventHelper::OnProcessNextEvent( 57 nsIThreadInternal* /* aThread */, bool /* aMayWait */) { 58 MOZ_CRASH("Should never be called!"); 59 } 60 61 NS_IMETHODIMP 62 RunAfterProcessingCurrentEventHelper::AfterProcessNextEvent( 63 nsIThreadInternal* aThread, bool /* aEventWasProcessed */) { 64 MOZ_ASSERT(aThread); 65 66 QM_WARNONLY_TRY(MOZ_TO_RESULT(aThread->RemoveObserver(this))); 67 68 auto callback = std::move(mCallback); 69 callback(); 70 71 return NS_OK; 72 } 73 74 nsresult RunAfterProcessingCurrentEvent(std::function<void()>&& aCallback) { 75 MOZ_DIAGNOSTIC_ASSERT( 76 !nsThreadPool::GetCurrentThreadPool(), 77 "Call to RunAfterProcessingCurrentEvent() from thread pool!"); 78 79 auto helper = MakeRefPtr<RunAfterProcessingCurrentEventHelper>(); 80 81 QM_TRY(MOZ_TO_RESULT(helper->Init(std::move(aCallback)))); 82 83 return NS_OK; 84 } 85 86 void SleepIfEnabled(StripAtomic<RelaxedAtomicUint32> aMirroredPrefValue) { 87 uint32_t pauseOnThreadMs = aMirroredPrefValue; 88 if (pauseOnThreadMs > 0) { 89 PR_Sleep(PR_MillisecondsToInterval(pauseOnThreadMs)); 90 } 91 } 92 93 } // namespace mozilla::dom::quota