#include "config.h"
#include <wtf/RunLoop.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/StdLibExtras.h>
#include <wtf/ThreadSpecific.h>
namespace WTF {
static RunLoop* s_mainRunLoop;
#if USE(WEB_THREAD)
static RunLoop* s_webRunLoop;
#endif
class RunLoop::Holder {
WTF_MAKE_FAST_ALLOCATED;
public:
Holder()
: m_runLoop(adoptRef(*new RunLoop))
{
}
RunLoop& runLoop() { return m_runLoop; }
private:
Ref<RunLoop> m_runLoop;
};
void RunLoop::initializeMain()
{
RELEASE_ASSERT(!s_mainRunLoop);
s_mainRunLoop = &RunLoop::current();
}
RunLoop& RunLoop::current()
{
static LazyNeverDestroyed<ThreadSpecific<Holder>> runLoopHolder;
static std::once_flag onceKey;
std::call_once(onceKey, [&] {
runLoopHolder.construct();
});
return runLoopHolder.get()->runLoop();
}
RunLoop& RunLoop::main()
{
ASSERT(s_mainRunLoop);
return *s_mainRunLoop;
}
#if USE(WEB_THREAD)
void RunLoop::initializeWeb()
{
RELEASE_ASSERT(!s_webRunLoop);
s_webRunLoop = &RunLoop::current();
}
RunLoop& RunLoop::web()
{
ASSERT(s_webRunLoop);
return *s_webRunLoop;
}
RunLoop* RunLoop::webIfExists()
{
return s_webRunLoop;
}
#endif
bool RunLoop::isMain()
{
ASSERT(s_mainRunLoop);
return s_mainRunLoop == &RunLoop::current();
}
void RunLoop::performWork()
{
bool didSuspendFunctions = false;
{
auto locker = holdLock(m_nextIterationLock);
while (!m_currentIteration.isEmpty())
m_nextIteration.prepend(m_currentIteration.takeLast());
m_currentIteration = std::exchange(m_nextIteration, { });
}
while (!m_currentIteration.isEmpty()) {
if (m_isFunctionDispatchSuspended) {
didSuspendFunctions = true;
break;
}
auto function = m_currentIteration.takeFirst();
function();
}
m_isFunctionDispatchSuspended = false;
m_hasSuspendedFunctions = didSuspendFunctions;
if (m_hasSuspendedFunctions)
wakeUp();
}
void RunLoop::dispatch(Function<void ()>&& function)
{
bool needsWakeup = false;
{
auto locker = holdLock(m_nextIterationLock);
needsWakeup = m_nextIteration.isEmpty();
m_nextIteration.append(WTFMove(function));
}
if (needsWakeup)
wakeUp();
}
void RunLoop::dispatchAfter(Seconds delay, Function<void()>&& function)
{
auto timer = new DispatchTimer(*this);
timer->setFunction([timer, function = WTFMove(function)] {
function();
delete timer;
});
timer->startOneShot(delay);
}
void RunLoop::suspendFunctionDispatchForCurrentCycle()
{
if (m_isFunctionDispatchSuspended || m_hasSuspendedFunctions)
return;
m_isFunctionDispatchSuspended = true;
wakeUp();
}
}