Title: [181220] trunk/Source/WTF
Revision
181220
Author
bfulg...@apple.com
Date
2015-03-07 20:57:54 -0800 (Sat, 07 Mar 2015)

Log Message

[Win] Revive WTF::WorkQueue on Windows
https://bugs.webkit.org/show_bug.cgi?id=142432

Reviewed by Darin Adler.

Revive the Windows implementation of WTF::WorkQueue.

* WTF.vcxproj/WTF.vcxproj:
* WTF.vcxproj/WTF.vcxproj.filters:
* wtf/WorkQueue.h:
* wtf/win/WorkItemWin.cpp: Added.
* wtf/win/WorkItemWin.h: Added.
* wtf/win/WorkQueueWin.cpp: Added.

Modified Paths

Added Paths

Diff

Modified: trunk/Source/WTF/ChangeLog (181219 => 181220)


--- trunk/Source/WTF/ChangeLog	2015-03-08 03:37:26 UTC (rev 181219)
+++ trunk/Source/WTF/ChangeLog	2015-03-08 04:57:54 UTC (rev 181220)
@@ -1,3 +1,19 @@
+2015-03-07  Brent Fulgham  <bfulg...@apple.com>
+
+        [Win] Revive WTF::WorkQueue on Windows
+        https://bugs.webkit.org/show_bug.cgi?id=142432
+
+        Reviewed by Darin Adler.
+
+        Revive the Windows implementation of WTF::WorkQueue.
+
+        * WTF.vcxproj/WTF.vcxproj:
+        * WTF.vcxproj/WTF.vcxproj.filters:
+        * wtf/WorkQueue.h:
+        * wtf/win/WorkItemWin.cpp: Added.
+        * wtf/win/WorkItemWin.h: Added.
+        * wtf/win/WorkQueueWin.cpp: Added.
+
 2015-03-06  Geoffrey Garen  <gga...@apple.com>
 
         Fix crashes seen on the the Windows buildbots after my last patch.

Modified: trunk/Source/WTF/WTF.vcxproj/WTF.vcxproj (181219 => 181220)


--- trunk/Source/WTF/WTF.vcxproj/WTF.vcxproj	2015-03-08 03:37:26 UTC (rev 181219)
+++ trunk/Source/WTF/WTF.vcxproj/WTF.vcxproj	2015-03-08 04:57:54 UTC (rev 181220)
@@ -149,7 +149,10 @@
     <ClCompile Include="..\wtf\unicode\UTF8.cpp" />
     <ClCompile Include="..\wtf\win\MainThreadWin.cpp" />
     <ClCompile Include="..\wtf\win\RunLoopWin.cpp" />
+    <ClCompile Include="..\wtf\win\WorkItemWin.cpp" />
+    <ClCompile Include="..\wtf\win\WorkQueueWin.cpp" />
     <ClCompile Include="..\wtf\win\WTFDLL.cpp" />
+    <ClCompile Include="..\wtf\WorkQueue.cpp" />
     <ClCompile Include="..\wtf\WTFThreadData.cpp" />
     <ClCompile Include="..\wtf\SchedulePairCF.cpp" />
   </ItemGroup>
@@ -306,6 +309,8 @@
     <ClInclude Include="..\wtf\Vector.h" />
     <ClInclude Include="..\wtf\VMTags.h" />
     <ClInclude Include="..\wtf\win\GDIObject.h" />
+    <ClInclude Include="..\wtf\win\WorkItemWin.h" />
+    <ClInclude Include="..\wtf\WorkQueue.h" />
     <ClInclude Include="..\wtf\WTFThreadData.h" />
   </ItemGroup>
   <ItemGroup>
@@ -769,4 +774,4 @@
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>
-</Project>
+</Project>
\ No newline at end of file

Modified: trunk/Source/WTF/WTF.vcxproj/WTF.vcxproj.filters (181219 => 181220)


--- trunk/Source/WTF/WTF.vcxproj/WTF.vcxproj.filters	2015-03-08 03:37:26 UTC (rev 181219)
+++ trunk/Source/WTF/WTF.vcxproj/WTF.vcxproj.filters	2015-03-08 04:57:54 UTC (rev 181220)
@@ -1,9 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
   <ItemGroup>
-    <Filter Include="win">
-      <UniqueIdentifier>{b7d787cb-2b2b-4898-8d03-b94115e596d1}</UniqueIdentifier>
-    </Filter>
     <Filter Include="dtoa">
       <UniqueIdentifier>{eaa36939-1976-495f-b9ed-90074ee4f2be}</UniqueIdentifier>
     </Filter>
@@ -28,6 +25,9 @@
     <Filter Include="wtf\gobject">
       <UniqueIdentifier>{edd6ccc8-e6ee-41ec-a58d-9404a30c0c7e}</UniqueIdentifier>
     </Filter>
+    <Filter Include="wtf\win">
+      <UniqueIdentifier>{b7d787cb-2b2b-4898-8d03-b94115e596d1}</UniqueIdentifier>
+    </Filter>
   </ItemGroup>
   <ItemGroup>
     <ClCompile Include="..\wtf\dtoa\bignum-dtoa.cc">
@@ -94,7 +94,7 @@
       <Filter>text</Filter>
     </ClCompile>
     <ClCompile Include="..\wtf\win\MainThreadWin.cpp">
-      <Filter>win</Filter>
+      <Filter>wtf\win</Filter>
     </ClCompile>
     <ClCompile Include="..\wtf\threads\win\BinarySemaphoreWin.cpp">
       <Filter>threads\win</Filter>
@@ -235,7 +235,7 @@
       <Filter>wtf</Filter>
     </ClCompile>
     <ClCompile Include="..\wtf\win\RunLoopWin.cpp">
-      <Filter>win</Filter>
+      <Filter>wtf\win</Filter>
     </ClCompile>
     <ClCompile Include="..\wtf\gobject\GMainLoopSource.cpp">
       <Filter>wtf\gobject</Filter>
@@ -248,8 +248,17 @@
     </ClCompile>
     <ClCompile Include="..\wtf\RefCounter.cpp" />
     <ClCompile Include="..\wtf\win\WTFDLL.cpp">
-      <Filter>win</Filter>
+      <Filter>wtf\win</Filter>
     </ClCompile>
+    <ClCompile Include="..\wtf\WorkQueue.cpp">
+      <Filter>wtf</Filter>
+    </ClCompile>
+    <ClCompile Include="..\wtf\win\WorkQueueWin.cpp">
+      <Filter>wtf\win</Filter>
+    </ClCompile>
+    <ClCompile Include="..\wtf\win\WorkItemWin.cpp">
+      <Filter>wtf\win</Filter>
+    </ClCompile>
   </ItemGroup>
   <ItemGroup>
     <ClInclude Include="..\wtf\dtoa\utils.h">
@@ -671,7 +680,7 @@
       <Filter>wtf</Filter>
     </ClInclude>
     <ClInclude Include="..\wtf\win\GDIObject.h">
-      <Filter>win</Filter>
+      <Filter>wtf\win</Filter>
     </ClInclude>
     <ClInclude Include="..\wtf\gobject\GlibUtilities.h">
       <Filter>wtf\gobject</Filter>
@@ -707,9 +716,15 @@
       <Filter>wtf\gobject</Filter>
     </ClInclude>
     <ClInclude Include="..\wtf\RefCounter.h" />
+    <ClInclude Include="..\wtf\WorkQueue.h">
+      <Filter>wtf</Filter>
+    </ClInclude>
+    <ClInclude Include="..\wtf\win\WorkItemWin.h">
+      <Filter>wtf\win</Filter>
+    </ClInclude>
   </ItemGroup>
   <ItemGroup>
     <None Include="WTFPostBuild.cmd" />
     <None Include="WTFPreBuild.cmd" />
   </ItemGroup>
-</Project>
+</Project>
\ No newline at end of file

Modified: trunk/Source/WTF/wtf/WorkQueue.h (181219 => 181220)


--- trunk/Source/WTF/wtf/WorkQueue.h	2015-03-08 03:37:26 UTC (rev 181219)
+++ trunk/Source/WTF/wtf/WorkQueue.h	2015-03-08 04:57:54 UTC (rev 181220)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2010, 2015 Apple Inc. All rights reserved.
  * Portions Copyright (c) 2010 Motorola Mobility, Inc.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -44,6 +44,10 @@
 #include <wtf/gobject/GRefPtr.h>
 #elif PLATFORM(EFL)
 #include <DispatchQueueEfl.h>
+#elif OS(WINDOWS)
+#include <wtf/HashMap.h>
+#include <wtf/Vector.h>
+#include <wtf/win/WorkItemWin.h>
 #endif
 
 namespace WTF {
@@ -84,6 +88,19 @@
     void platformInitialize(const char* name, Type, QOS);
     void platformInvalidate();
 
+#if OS(WINDOWS)
+    static void CALLBACK handleCallback(void* context, BOOLEAN timerOrWaitFired);
+    static void CALLBACK timerCallback(void* context, BOOLEAN timerOrWaitFired);
+    static DWORD WINAPI workThreadCallback(void* context);
+
+    bool tryRegisterAsWorkThread();
+    void unregisterAsWorkThread();
+    void performWorkOnRegisteredWorkThread();
+
+    static void unregisterWaitAndDestroyItemSoon(PassRefPtr<HandleWorkItem>);
+    static DWORD WINAPI unregisterWaitAndDestroyItemCallback(void* context);
+#endif
+
 #if OS(DARWIN)
     static void executeFunction(void*);
     dispatch_queue_t m_dispatchQueue;
@@ -95,6 +112,16 @@
     GMainLoopSource m_socketEventSource;
 #elif PLATFORM(EFL)
     RefPtr<DispatchQueue> m_dispatchQueue;
+#elif OS(WINDOWS)
+    volatile LONG m_isWorkThreadRegistered;
+
+    Mutex m_workItemQueueLock;
+    Vector<RefPtr<WorkItemWin>> m_workItemQueue;
+
+    Mutex m_handlesLock;
+    HashMap<HANDLE, RefPtr<HandleWorkItem>> m_handles;
+
+    HANDLE m_timerQueue;
 #endif
 };
 

Added: trunk/Source/WTF/wtf/win/WorkItemWin.cpp (0 => 181220)


--- trunk/Source/WTF/wtf/win/WorkItemWin.cpp	                        (rev 0)
+++ trunk/Source/WTF/wtf/win/WorkItemWin.cpp	2015-03-08 04:57:54 UTC (rev 181220)
@@ -0,0 +1,68 @@
+/*
+* Copyright (C) 2010, 2015 Apple Inc. All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+* 1. Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+* 2. Redistributions in binary form must reproduce the above copyright
+*    notice, this list of conditions and the following disclaimer in the
+*    documentation and/or other materials provided with the distribution.
+*
+* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include "config.h"
+#include "WorkItemWin.h"
+
+#include <Windows.h>
+#include <wtf/Threading.h>
+#include <wtf/WorkQueue.h>
+
+namespace WTF {
+
+WorkItemWin::WorkItemWin(std::function<void()> function, WorkQueue* queue)
+    : m_function(function)
+    , m_queue(queue)
+{
+}
+
+RefPtr<WorkItemWin> WorkItemWin::create(std::function<void()> function, WorkQueue* queue)
+{
+    return adoptRef(new WorkItemWin(function, queue));
+}
+
+WorkItemWin::~WorkItemWin()
+{
+}
+
+HandleWorkItem::HandleWorkItem(HANDLE handle, const std::function<void()>& function, WorkQueue* queue)
+    : WorkItemWin(function, queue)
+    , m_handle(handle)
+    , m_waitHandle(0)
+{
+    ASSERT_ARG(handle, handle);
+}
+
+RefPtr<HandleWorkItem> HandleWorkItem::createByAdoptingHandle(HANDLE handle, const std::function<void()>& function, WorkQueue* queue)
+{
+    return adoptRef(new HandleWorkItem(handle, function, queue));
+}
+
+HandleWorkItem::~HandleWorkItem()
+{
+    ::CloseHandle(m_handle);
+}
+
+} // namespace WTF

Added: trunk/Source/WTF/wtf/win/WorkItemWin.h (0 => 181220)


--- trunk/Source/WTF/wtf/win/WorkItemWin.h	                        (rev 0)
+++ trunk/Source/WTF/wtf/win/WorkItemWin.h	2015-03-08 04:57:54 UTC (rev 181220)
@@ -0,0 +1,72 @@
+/*
+* Copyright (C) 2010, 2015 Apple Inc. All rights reserved.
+* Portions Copyright (c) 2010 Motorola Mobility, Inc.  All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+* 1. Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+* 2. Redistributions in binary form must reproduce the above copyright
+*    notice, this list of conditions and the following disclaimer in the
+*    documentation and/or other materials provided with the distribution.
+*
+* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef WorkItemWin_h
+#define WorkItemWin_h
+
+#include <Windows.h>
+#include <functional>
+#include <wtf/RefPtr.h>
+#include <wtf/ThreadSafeRefCounted.h>
+
+namespace WTF {
+
+class WorkQueue;
+
+class WorkItemWin : public ThreadSafeRefCounted<WorkItemWin> {
+public:
+    static RefPtr<WorkItemWin> create(std::function<void()>, WorkQueue*);
+    virtual ~WorkItemWin();
+
+    std::function<void()>& function() { return m_function; }
+    WorkQueue* queue() const { return m_queue.get(); }
+
+protected:
+    WorkItemWin(std::function<void()>, WorkQueue*);
+
+private:
+    std::function<void()> m_function;
+    RefPtr<WorkQueue> m_queue;
+};
+
+class HandleWorkItem : public WorkItemWin {
+public:
+    static RefPtr<HandleWorkItem> createByAdoptingHandle(HANDLE, const std::function<void()>&, WorkQueue*);
+    virtual ~HandleWorkItem();
+
+    void setWaitHandle(HANDLE waitHandle) { m_waitHandle = waitHandle; }
+    HANDLE waitHandle() const { return m_waitHandle; }
+
+private:
+    HandleWorkItem(HANDLE, const std::function<void()>&, WorkQueue*);
+
+    HANDLE m_handle;
+    HANDLE m_waitHandle;
+};
+
+}
+
+#endif

Added: trunk/Source/WTF/wtf/win/WorkQueueWin.cpp (0 => 181220)


--- trunk/Source/WTF/wtf/win/WorkQueueWin.cpp	                        (rev 0)
+++ trunk/Source/WTF/wtf/win/WorkQueueWin.cpp	2015-03-08 04:57:54 UTC (rev 181220)
@@ -0,0 +1,234 @@
+/*
+* Copyright (C) 2010, 2015 Apple Inc. All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+* 1. Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+* 2. Redistributions in binary form must reproduce the above copyright
+*    notice, this list of conditions and the following disclaimer in the
+*    documentation and/or other materials provided with the distribution.
+*
+* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include "config.h"
+#include "WorkQueue.h"
+
+#include <wtf/MathExtras.h>
+#include <wtf/Threading.h>
+#include <wtf/win/WorkItemWin.h>
+
+namespace WTF {
+
+void WorkQueue::handleCallback(void* context, BOOLEAN timerOrWaitFired)
+{
+    ASSERT_ARG(context, context);
+    ASSERT_ARG(timerOrWaitFired, !timerOrWaitFired);
+
+    WorkItemWin* item = static_cast<WorkItemWin*>(context);
+    RefPtr<WorkQueue> queue = item->queue();
+
+    {
+        MutexLocker lock(queue->m_workItemQueueLock);
+        queue->m_workItemQueue.append(item);
+
+        // If no other thread is performing work, we can do it on this thread.
+        if (!queue->tryRegisterAsWorkThread()) {
+            // Some other thread is performing work. Since we hold the queue lock, we can be sure
+            // that the work thread is not exiting due to an empty queue and will process the work
+            // item we just added to it. If we weren't holding the lock we'd have to signal
+            // m_performWorkEvent to make sure the work item got picked up.
+            return;
+        }
+    }
+
+    queue->performWorkOnRegisteredWorkThread();
+}
+
+DWORD WorkQueue::workThreadCallback(void* context)
+{
+    ASSERT_ARG(context, context);
+
+    WorkQueue* queue = static_cast<WorkQueue*>(context);
+
+    if (!queue->tryRegisterAsWorkThread())
+        return 0;
+
+    queue->performWorkOnRegisteredWorkThread();
+    return 0;
+}
+
+void WorkQueue::performWorkOnRegisteredWorkThread()
+{
+    ASSERT(m_isWorkThreadRegistered);
+
+    m_workItemQueueLock.lock();
+
+    while (!m_workItemQueue.isEmpty()) {
+        Vector<RefPtr<WorkItemWin>> workItemQueue;
+        m_workItemQueue.swap(workItemQueue);
+
+        // Allow more work to be scheduled while we're not using the queue directly.
+        m_workItemQueueLock.unlock();
+        for (auto& workItem : workItemQueue)
+            workItem->function()();
+        m_workItemQueueLock.lock();
+    }
+
+    // One invariant we maintain is that any work scheduled while a work thread is registered will
+    // be handled by that work thread. Unregister as the work thread while the queue lock is still
+    // held so that no work can be scheduled while we're still registered.
+    unregisterAsWorkThread();
+
+    m_workItemQueueLock.unlock();
+}
+
+void WorkQueue::platformInitialize(const char* name, Type, QOS)
+{
+    m_isWorkThreadRegistered = 0;
+    m_timerQueue = ::CreateTimerQueue();
+    ASSERT_WITH_MESSAGE(m_timerQueue, "::CreateTimerQueue failed with error %lu", ::GetLastError());
+}
+
+bool WorkQueue::tryRegisterAsWorkThread()
+{
+    LONG result = ::InterlockedCompareExchange(&m_isWorkThreadRegistered, 1, 0);
+    ASSERT(!result || result == 1);
+    return !result;
+}
+
+void WorkQueue::unregisterAsWorkThread()
+{
+    LONG result = ::InterlockedCompareExchange(&m_isWorkThreadRegistered, 0, 1);
+    ASSERT_UNUSED(result, result == 1);
+}
+
+void WorkQueue::platformInvalidate()
+{
+#if !ASSERT_DISABLED
+    MutexLocker lock(m_handlesLock);
+    ASSERT(m_handles.isEmpty());
+#endif
+
+    // FIXME: We need to ensure that any timer-queue timers that fire after this point don't try to
+    // access this WorkQueue <http://webkit.org/b/44690>.
+    ::DeleteTimerQueueEx(m_timerQueue, 0);
+}
+
+void WorkQueue::dispatch(std::function<void()> function)
+{
+    MutexLocker locker(m_workItemQueueLock);
+    ref();
+    m_workItemQueue.append(WorkItemWin::create(function, this));
+
+    // Spawn a work thread to perform the work we just added. As an optimization, we avoid
+    // spawning the thread if a work thread is already registered. This prevents multiple work
+    // threads from being spawned in most cases. (Note that when a work thread has been spawned but
+    // hasn't registered itself yet, m_isWorkThreadRegistered will be false and we'll end up
+    // spawning a second work thread here. But work thread registration process will ensure that
+    // only one thread actually ends up performing work.)
+    if (!m_isWorkThreadRegistered)
+        ::QueueUserWorkItem(workThreadCallback, this, WT_EXECUTEDEFAULT);
+}
+
+struct TimerContext : public ThreadSafeRefCounted<TimerContext> {
+    static RefPtr<TimerContext> create() { return adoptRef(new TimerContext); }
+
+    WorkQueue* queue;
+    std::function<void()> function;
+    Mutex timerMutex;
+    HANDLE timer;
+
+private:
+    TimerContext()
+        : queue(nullptr)
+        , timer(0)
+    {
+    }
+};
+
+void WorkQueue::timerCallback(void* context, BOOLEAN timerOrWaitFired)
+{
+    ASSERT_ARG(context, context);
+    ASSERT_UNUSED(timerOrWaitFired, timerOrWaitFired);
+
+    // Balanced by leakRef in scheduleWorkAfterDelay.
+    RefPtr<TimerContext> timerContext = adoptRef(static_cast<TimerContext*>(context));
+
+    timerContext->queue->dispatch(timerContext->function);
+
+    MutexLocker lock(timerContext->timerMutex);
+    ASSERT(timerContext->timer);
+    ASSERT(timerContext->queue->m_timerQueue);
+    if (!::DeleteTimerQueueTimer(timerContext->queue->m_timerQueue, timerContext->timer, 0)) {
+        // Getting ERROR_IO_PENDING here means that the timer will be destroyed once the callback is done executing.
+        ASSERT_WITH_MESSAGE(::GetLastError() == ERROR_IO_PENDING, "::DeleteTimerQueueTimer failed with error %lu", ::GetLastError());
+    }
+}
+
+void WorkQueue::dispatchAfter(std::chrono::nanoseconds duration, std::function<void()> function)
+{
+    ASSERT(m_timerQueue);
+    ref();
+
+    RefPtr<TimerContext> context = TimerContext::create();
+    context->queue = this;
+    context->function = function;
+
+    {
+        // The timer callback could fire before ::CreateTimerQueueTimer even returns, so we protect
+        // context->timer with a mutex to ensure the timer callback doesn't access it before the
+        // timer handle has been stored in it.
+        MutexLocker lock(context->timerMutex);
+
+        // Since our timer callback is quick, we can execute in the timer thread itself and avoid
+        // an extra thread switch over to a worker thread.
+        int64_t milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
+        if (!::CreateTimerQueueTimer(&context->timer, m_timerQueue, timerCallback, context.get(), clampTo<DWORD>(milliseconds), 0, WT_EXECUTEINTIMERTHREAD)) {
+            ASSERT_WITH_MESSAGE(false, "::CreateTimerQueueTimer failed with error %lu", ::GetLastError());
+            return;
+        }
+    }
+
+    // The timer callback will handle destroying context.
+    context.release().leakRef();
+}
+
+void WorkQueue::unregisterWaitAndDestroyItemSoon(PassRefPtr<HandleWorkItem> item)
+{
+    // We're going to make a blocking call to ::UnregisterWaitEx before closing the handle. (The
+    // blocking version of ::UnregisterWaitEx is much simpler than the non-blocking version.) If we
+    // do this on the current thread, we'll deadlock if we're currently in a callback function for
+    // the wait we're unregistering. So instead we do it asynchronously on some other worker thread.
+
+    ::QueueUserWorkItem(unregisterWaitAndDestroyItemCallback, item.leakRef(), WT_EXECUTEDEFAULT);
+}
+
+DWORD WINAPI WorkQueue::unregisterWaitAndDestroyItemCallback(void* context)
+{
+    ASSERT_ARG(context, context);
+    RefPtr<HandleWorkItem> item = adoptRef(static_cast<HandleWorkItem*>(context));
+
+    // Now that we know we're not in a callback function for the wait we're unregistering, we can
+    // make a blocking call to ::UnregisterWaitEx.
+    if (!::UnregisterWaitEx(item->waitHandle(), INVALID_HANDLE_VALUE)) {
+        DWORD error = ::GetLastError();
+        ASSERT_NOT_REACHED();
+    }
+
+    return 0;
+}
+
+} // namespace WTF
_______________________________________________
webkit-changes mailing list
webkit-changes@lists.webkit.org
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to