Line data Source code
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 : #ifndef MOZILLA_AUTOTASKQUEUE_H_
8 : #define MOZILLA_AUTOTASKQUEUE_H_
9 :
10 : #include "mozilla/RefPtr.h"
11 : #include "mozilla/SharedThreadPool.h"
12 : #include "mozilla/SystemGroup.h"
13 : #include "mozilla/TaskQueue.h"
14 :
15 : namespace mozilla {
16 :
17 : // A convenience TaskQueue not requiring explicit shutdown.
18 : class AutoTaskQueue : public AbstractThread
19 : {
20 : public:
21 : explicit AutoTaskQueue(already_AddRefed<SharedThreadPool> aPool,
22 : bool aSupportsTailDispatch = false)
23 : : AbstractThread(aSupportsTailDispatch)
24 : , mTaskQueue(new TaskQueue(Move(aPool), aSupportsTailDispatch))
25 : {}
26 :
27 0 : AutoTaskQueue(already_AddRefed<SharedThreadPool> aPool,
28 : const char* aName,
29 : bool aSupportsTailDispatch = false)
30 0 : : AbstractThread(aSupportsTailDispatch)
31 0 : , mTaskQueue(new TaskQueue(Move(aPool), aName, aSupportsTailDispatch))
32 0 : {}
33 :
34 0 : TaskDispatcher& TailDispatcher() override
35 : {
36 0 : return mTaskQueue->TailDispatcher();
37 : }
38 :
39 0 : void Dispatch(already_AddRefed<nsIRunnable> aRunnable,
40 : DispatchFailureHandling aFailureHandling = AssertDispatchSuccess,
41 : DispatchReason aReason = NormalDispatch) override
42 : {
43 0 : mTaskQueue->Dispatch(Move(aRunnable), aFailureHandling, aReason);
44 0 : }
45 :
46 : // Prevent a GCC warning about the other overload of Dispatch being hidden.
47 : using AbstractThread::Dispatch;
48 :
49 : // Blocks until all tasks finish executing.
50 : void AwaitIdle() { mTaskQueue->AwaitIdle(); }
51 :
52 : bool IsEmpty() { return mTaskQueue->IsEmpty(); }
53 :
54 : // Returns true if the current thread is currently running a Runnable in
55 : // the task queue.
56 0 : bool IsCurrentThreadIn() override { return mTaskQueue->IsCurrentThreadIn(); }
57 :
58 : private:
59 0 : ~AutoTaskQueue()
60 0 : {
61 0 : RefPtr<TaskQueue> taskqueue = mTaskQueue;
62 : nsCOMPtr<nsIRunnable> task =
63 0 : NS_NewRunnableFunction("AutoTaskQueue::~AutoTaskQueue",
64 0 : [taskqueue]() { taskqueue->BeginShutdown(); });
65 0 : SystemGroup::Dispatch("~AutoTaskQueue", TaskCategory::Other, task.forget());
66 0 : }
67 : RefPtr<TaskQueue> mTaskQueue;
68 : };
69 :
70 : } // namespace mozilla
71 :
72 : #endif
|