AutoTaskQueue.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #ifndef MOZILLA_AUTOTASKQUEUE_H_
  6. #define MOZILLA_AUTOTASKQUEUE_H_
  7. #include "mozilla/RefPtr.h"
  8. #include "mozilla/SharedThreadPool.h"
  9. #include "mozilla/TaskQueue.h"
  10. namespace mozilla {
  11. // A convenience TaskQueue not requiring explicit shutdown.
  12. class AutoTaskQueue : public AbstractThread
  13. {
  14. public:
  15. explicit AutoTaskQueue(already_AddRefed<SharedThreadPool> aPool, bool aSupportsTailDispatch = false)
  16. : AbstractThread(aSupportsTailDispatch)
  17. , mTaskQueue(new TaskQueue(Move(aPool), aSupportsTailDispatch))
  18. {}
  19. TaskDispatcher& TailDispatcher() override
  20. {
  21. return mTaskQueue->TailDispatcher();
  22. }
  23. void Dispatch(already_AddRefed<nsIRunnable> aRunnable,
  24. DispatchFailureHandling aFailureHandling = AssertDispatchSuccess,
  25. DispatchReason aReason = NormalDispatch) override
  26. {
  27. mTaskQueue->Dispatch(Move(aRunnable), aFailureHandling, aReason);
  28. }
  29. // Blocks until all tasks finish executing.
  30. void AwaitIdle() { mTaskQueue->AwaitIdle(); }
  31. bool IsEmpty() { return mTaskQueue->IsEmpty(); }
  32. // Returns true if the current thread is currently running a Runnable in
  33. // the task queue.
  34. bool IsCurrentThreadIn() override { return mTaskQueue->IsCurrentThreadIn(); }
  35. private:
  36. ~AutoTaskQueue()
  37. {
  38. RefPtr<TaskQueue> taskqueue = mTaskQueue;
  39. nsCOMPtr<nsIRunnable> task =
  40. NS_NewRunnableFunction([taskqueue]() { taskqueue->BeginShutdown(); });
  41. AbstractThread::MainThread()->Dispatch(task.forget());
  42. }
  43. RefPtr<TaskQueue> mTaskQueue;
  44. };
  45. } // namespace mozilla
  46. #endif