GenericTaskQueue.h [plain text]
#pragma once
#include "Timer.h"
#include <wtf/Deque.h>
#include <wtf/Function.h>
#include <wtf/WeakPtr.h>
namespace WebCore {
template <typename T>
class TaskDispatcher {
public:
TaskDispatcher(T& context)
: m_context(context)
{
}
void postTask(WTF::Function<void()>&& f)
{
m_context.postTask(WTFMove(f));
}
private:
T& m_context;
};
template<>
class TaskDispatcher<Timer> : public CanMakeWeakPtr<TaskDispatcher<Timer>> {
public:
TaskDispatcher();
void postTask(WTF::Function<void()>&&);
private:
static Timer& sharedTimer();
static void sharedTimerFired();
static Deque<WeakPtr<TaskDispatcher<Timer>>>& pendingDispatchers();
void dispatchOneTask();
Deque<WTF::Function<void()>> m_pendingTasks;
};
template <typename T>
class GenericTaskQueue : public CanMakeWeakPtr<GenericTaskQueue<T>> {
public:
GenericTaskQueue()
: m_dispatcher()
{
}
GenericTaskQueue(T& t)
: m_dispatcher(t)
{
}
typedef WTF::Function<void ()> TaskFunction;
void enqueueTask(TaskFunction&& task)
{
if (m_isClosed)
return;
++m_pendingTasks;
m_dispatcher.postTask([weakThis = makeWeakPtr(*this), task = WTFMove(task)] {
if (!weakThis)
return;
ASSERT(weakThis->m_pendingTasks);
--weakThis->m_pendingTasks;
task();
});
}
void close()
{
cancelAllTasks();
m_isClosed = true;
}
void cancelAllTasks()
{
CanMakeWeakPtr<GenericTaskQueue<T>>::weakPtrFactory().revokeAll();
m_pendingTasks = 0;
}
bool hasPendingTasks() const { return m_pendingTasks; }
private:
TaskDispatcher<T> m_dispatcher;
unsigned m_pendingTasks { 0 };
bool m_isClosed { false };
};
}