#include "config.h"
#include "StorageThread.h"
#include "StorageAreaSync.h"
#include <wtf/AutodrainedPool.h>
#include <wtf/HashSet.h>
#include <wtf/MainThread.h>
namespace WebCore {
static HashSet<StorageThread*>& activeStorageThreads()
{
ASSERT(isMainThread());
DEPRECATED_DEFINE_STATIC_LOCAL(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(const Function<void ()>& function)
{
ASSERT(isMainThread());
ASSERT(!m_queue.killed() && m_threadID);
m_queue.append(std::make_unique<Function<void ()>>(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 ()>>(bind(&StorageThread::performTerminate, this)));
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(bind(WTF::releaseFastMallocFreeMemory));
}
}