#include "StorageThread.h"
#include <wtf/AutodrainedPool.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()
: m_threadID(0)
{
ASSERT(isMainThread());
}
StorageThread::~StorageThread()
{
ASSERT(isMainThread());
ASSERT(!m_threadID);
}
bool StorageThread::start()
{
ASSERT(isMainThread());
if (!m_threadID)
m_threadID = createThread(StorageThread::threadEntryPointCallback, this, "WebCore: LocalStorage");
activeStorageThreads().add(this);
return m_threadID;
}
void StorageThread::threadEntryPointCallback(void* thread)
{
static_cast<StorageThread*>(thread)->threadEntryPoint();
}
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_threadID);
m_queue.append(std::make_unique<Function<void ()>>(WTFMove(function)));
}
void StorageThread::terminate()
{
ASSERT(isMainThread());
ASSERT(!m_queue.killed() && m_threadID);
activeStorageThreads().remove(this);
if (!m_threadID)
return;
m_queue.append(std::make_unique<Function<void ()>>([this] {
performTerminate();
}));
waitForThreadCompletion(m_threadID);
ASSERT(m_queue.killed());
m_threadID = 0;
}
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();
});
}
}
}