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:
TaskDispatcher();
void postTask(WTF::Function<void()>&&);
private:
static Timer& sharedTimer();
static void sharedTimerFired();
static Deque<WeakPtr<TaskDispatcher<Timer>>>& pendingDispatchers();
void dispatchOneTask();
WeakPtrFactory<TaskDispatcher> m_weakPtrFactory;
Deque<WTF::Function<void()>> m_pendingTasks;
};
template <typename T>
class GenericTaskQueue {
public:
GenericTaskQueue()
: m_weakPtrFactory(this)
, m_dispatcher()
{
}
GenericTaskQueue(T& t)
: m_weakPtrFactory(this)
, m_dispatcher(t)
{
}
typedef WTF::Function<void ()> TaskFunction;
void enqueueTask(TaskFunction&& task)
{
if (m_isClosed)
return;
++m_pendingTasks;
auto weakThis = m_weakPtrFactory.createWeakPtr();
m_dispatcher.postTask([weakThis, task = WTFMove(task)] {
if (!weakThis)
return;
ASSERT(weakThis->m_pendingTasks);
--weakThis->m_pendingTasks;
task();
});
}
void close()
{
cancelAllTasks();
m_isClosed = true;
}
void cancelAllTasks()
{
m_weakPtrFactory.revokeAll();
m_pendingTasks = 0;
}
bool hasPendingTasks() const { return m_pendingTasks; }
private:
WeakPtrFactory<GenericTaskQueue> m_weakPtrFactory;
TaskDispatcher<T> m_dispatcher;
unsigned m_pendingTasks { 0 };
bool m_isClosed { false };
};
}