#include "StorageThread.h"
#include <wtf/AutodrainedPool.h>
#include <wtf/HashSet.h>
#include <wtf/MainThread.h>
#include <wtf/NeverDestroyed.h>
namespace WebCore {
static HashSet<StorageThread*>& activeStorageThreads()
{
ASSERT(isMainThread());
static NeverDestroyed<HashSet<StorageThread*>> threads;
return threads;
}
StorageThread::StorageThread()
{
ASSERT(isMainThread());
}
StorageThread::~StorageThread()
{
ASSERT(isMainThread());
ASSERT(!m_thread);
}
bool StorageThread::start()
{
ASSERT(isMainThread());
if (!m_thread) {
m_thread = Thread::create("WebCore: LocalStorage", [this] {
threadEntryPoint();
});
}
activeStorageThreads().add(this);
return m_thread;
}
void StorageThread::threadEntryPoint()
{
ASSERT(!isMainThread());
while (auto function = m_queue.waitForMessage()) {
AutodrainedPool pool;
(*function)();
}
}
void StorageThread::dispatch(Function<void ()>&& function)
{
ASSERT(isMainThread());
ASSERT(!m_queue.killed() && m_thread);
m_queue.append(std::make_unique<Function<void ()>>(WTFMove(function)));
}
void StorageThread::terminate()
{
ASSERT(isMainThread());
ASSERT(!m_queue.killed() && m_thread);
activeStorageThreads().remove(this);
if (!m_thread)
return;
m_queue.append(std::make_unique<Function<void ()>>([this] {
performTerminate();
}));
m_thread->waitForCompletion();
ASSERT(m_queue.killed());
m_thread = nullptr;
}
void StorageThread::performTerminate()
{
ASSERT(!isMainThread());
m_queue.kill();
}
void StorageThread::releaseFastMallocFreeMemoryInAllThreads()
{
HashSet<StorageThread*>& threads = activeStorageThreads();
for (HashSet<StorageThread*>::iterator it = threads.begin(), end = threads.end(); it != end; ++it) {
(*it)->dispatch([]() {
WTF::releaseFastMallocFreeMemory();
});
}
}
}