[llvm] [orc-rt] Replace TaskDispatcher with Session-supplied wrapper-runner. (PR #204965)
Lang Hames via llvm-commits
llvm-commits at lists.llvm.org
Sun Jun 21 01:19:47 PDT 2026
https://github.com/lhames created https://github.com/llvm/llvm-project/pull/204965
TaskDispatcher was only used to run wrapper-function calls that originated from the controller. Replace it with a callable type:
Session::RunWrapperCall = move_only_function<void(
orc_rt_SessionRef, uint64_t, orc_rt_WrapperFunctionReturn,
orc_rt_WrapperFunction, WrapperFunctionBuffer)>
Each call carries an outstanding ManagedCodeTaskGroup token; the runner must eventually invoke Fn (which calls Return) or call Return directly to bail out, otherwise Session shutdown blocks indefinitely.
Clients can supply any callable that satisfies the contract above. The new QueueingRunner and ThreadPoolRunner classes (replacing QueueingTaskDispatcher and ThreadPoolTaskDispatcher, respectively) are provided as off-the-shelf options.
>From 9e82c692cacdcfd7fb12618621112c2ad3fdb2c7 Mon Sep 17 00:00:00 2001
From: Lang Hames <lhames at gmail.com>
Date: Sun, 21 Jun 2026 14:45:35 +1000
Subject: [PATCH] [orc-rt] Replace TaskDispatcher with Session-supplied
wrapper-runner.
TaskDispatcher was only used to run wrapper-function calls that originated
from the controller. Replace it with a callable type:
Session::RunWrapperCall = move_only_function<void(
orc_rt_SessionRef, uint64_t, orc_rt_WrapperFunctionReturn,
orc_rt_WrapperFunction, WrapperFunctionBuffer)>
Each call carries an outstanding ManagedCodeTaskGroup token; the runner
must eventually invoke Fn (which calls Return) or call Return directly to
bail out, otherwise Session shutdown blocks indefinitely.
Clients can supply any callable that satisfies the contract above. The new
QueueingRunner and ThreadPoolRunner classes (replacing QueueingTaskDispatcher
and ThreadPoolTaskDispatcher, respectively) are provided as off-the-shelf
options.
---
orc-rt/include/CMakeLists.txt | 5 +-
orc-rt/include/orc-rt/QueueingRunner.h | 82 +++++
.../include/orc-rt/QueueingTaskDispatcher.h | 73 -----
orc-rt/include/orc-rt/Session.h | 32 +-
orc-rt/include/orc-rt/TaskDispatcher.h | 64 ----
orc-rt/include/orc-rt/ThreadPoolRunner.h | 72 +++++
.../include/orc-rt/ThreadPoolTaskDispatcher.h | 48 ---
orc-rt/lib/executor/CMakeLists.txt | 4 +-
.../lib/executor/QueueingTaskDispatcher.cpp | 73 -----
orc-rt/lib/executor/Session.cpp | 7 +-
orc-rt/lib/executor/TaskDispatcher.cpp | 20 --
orc-rt/lib/executor/ThreadPoolRunner.cpp | 69 +++++
.../lib/executor/ThreadPoolTaskDispatcher.cpp | 70 -----
orc-rt/unittests/BootstrapInfoTest.cpp | 35 +--
orc-rt/unittests/CMakeLists.txt | 4 +-
orc-rt/unittests/CommonTestUtils.h | 21 +-
.../unittests/NativeDylibManagerSPSCITest.cpp | 4 +-
orc-rt/unittests/NativeDylibManagerTest.cpp | 27 +-
orc-rt/unittests/QueueingRunnerTest.cpp | 133 ++++++++
.../unittests/QueueingTaskDispatcherTest.cpp | 291 ------------------
orc-rt/unittests/SessionTest.cpp | 226 +++++---------
.../SimpleNativeMemoryMapSPSCITest.cpp | 4 +-
.../unittests/SimpleNativeMemoryMapTest.cpp | 25 +-
orc-rt/unittests/ThreadPoolRunnerTest.cpp | 153 +++++++++
.../ThreadPoolTaskDispatcherTest.cpp | 110 -------
25 files changed, 668 insertions(+), 984 deletions(-)
create mode 100644 orc-rt/include/orc-rt/QueueingRunner.h
delete mode 100644 orc-rt/include/orc-rt/QueueingTaskDispatcher.h
delete mode 100644 orc-rt/include/orc-rt/TaskDispatcher.h
create mode 100644 orc-rt/include/orc-rt/ThreadPoolRunner.h
delete mode 100644 orc-rt/include/orc-rt/ThreadPoolTaskDispatcher.h
delete mode 100644 orc-rt/lib/executor/QueueingTaskDispatcher.cpp
delete mode 100644 orc-rt/lib/executor/TaskDispatcher.cpp
create mode 100644 orc-rt/lib/executor/ThreadPoolRunner.cpp
delete mode 100644 orc-rt/lib/executor/ThreadPoolTaskDispatcher.cpp
create mode 100644 orc-rt/unittests/QueueingRunnerTest.cpp
delete mode 100644 orc-rt/unittests/QueueingTaskDispatcherTest.cpp
create mode 100644 orc-rt/unittests/ThreadPoolRunnerTest.cpp
delete mode 100644 orc-rt/unittests/ThreadPoolTaskDispatcherTest.cpp
diff --git a/orc-rt/include/CMakeLists.txt b/orc-rt/include/CMakeLists.txt
index 61c0c534b8327..0a2b91cfda710 100644
--- a/orc-rt/include/CMakeLists.txt
+++ b/orc-rt/include/CMakeLists.txt
@@ -17,7 +17,7 @@ set(ORC_RT_HEADERS
orc-rt/Math.h
orc-rt/MemoryFlags.h
orc-rt/NativeDylibManager.h
- orc-rt/QueueingTaskDispatcher.h
+ orc-rt/QueueingRunner.h
orc-rt/RTTI.h
orc-rt/ScopeExit.h
orc-rt/Service.h
@@ -34,8 +34,7 @@ set(ORC_RT_HEADERS
orc-rt/SPSWrapperFunction.h
orc-rt/SPSWrapperFunctionBuffer.h
orc-rt/TaskGroup.h
- orc-rt/TaskDispatcher.h
- orc-rt/ThreadPoolTaskDispatcher.h
+ orc-rt/ThreadPoolRunner.h
orc-rt/WrapperFunction.h
orc-rt/bind.h
orc-rt/bit.h
diff --git a/orc-rt/include/orc-rt/QueueingRunner.h b/orc-rt/include/orc-rt/QueueingRunner.h
new file mode 100644
index 0000000000000..b3225f149ba53
--- /dev/null
+++ b/orc-rt/include/orc-rt/QueueingRunner.h
@@ -0,0 +1,82 @@
+//===------------------------ QueueingRunner.h ------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// QueueingRunner class template.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef ORC_RT_QUEUEINGRUNNER_H
+#define ORC_RT_QUEUEINGRUNNER_H
+
+#include "orc-rt/WrapperFunction.h"
+
+#include "orc-rt-c/CoreTypes.h"
+#include "orc-rt-c/WrapperFunction.h"
+
+#include <cstdint>
+#include <utility>
+
+namespace orc_rt {
+
+/// A wrapper-call runner that pushes incoming calls onto a caller-owned work
+/// queue, leaving the caller free to drain the queue however and whenever
+/// they choose.
+///
+/// QueueingRunner is intended for use on systems where threads are not
+/// available, and for unit tests. For most uses of the ORC runtime,
+/// alternatives like ThreadPoolRunner are preferred.
+///
+/// WorkQueue may be any container that stores `void()`-callable values and
+/// supports `push_back`, `pop_back`, `pop_front`, `back()`, `front()`, and
+/// `empty()` (e.g. `std::deque<move_only_function<void()>>`). In
+/// multi-threaded setups the WorkQueue type itself is responsible for
+/// providing whatever synchronization is needed for concurrent push and
+/// drain operations.
+template <typename WorkQueue> class QueueingRunner {
+public:
+ QueueingRunner(WorkQueue &Pending) : Pending(Pending) {}
+
+ /// Enqueue a wrapper-function call to be run later.
+ void operator()(orc_rt_SessionRef S, uint64_t CallId,
+ orc_rt_WrapperFunctionReturn Return,
+ orc_rt_WrapperFunction Fn, WrapperFunctionBuffer ArgBytes) {
+ Pending.push_back([=, ArgBytes = std::move(ArgBytes)]() mutable {
+ Fn(S, CallId, Return, ArgBytes.release());
+ });
+ }
+
+ /// Run all currently-queued calls in last-in-first-out order, returning when
+ /// the queue is empty. Calls enqueued during draining are run too.
+ static void runLIFOUntilEmpty(WorkQueue &Q) {
+ while (!Q.empty()) {
+ auto Call = std::move(Q.back());
+ Q.pop_back();
+ Call();
+ }
+ }
+
+ /// Run all currently-queued calls in first-in-first-out order, returning
+ /// when the queue is empty. Calls enqueued during draining are run too.
+ static void runFIFOUntilEmpty(WorkQueue &Q) {
+ while (!Q.empty()) {
+ auto Call = std::move(Q.front());
+ Q.pop_front();
+ Call();
+ }
+ }
+
+private:
+ WorkQueue &Pending;
+};
+
+template <typename WorkQueue>
+QueueingRunner(WorkQueue &) -> QueueingRunner<WorkQueue>;
+
+} // namespace orc_rt
+
+#endif // ORC_RT_QUEUEINGRUNNER_H
diff --git a/orc-rt/include/orc-rt/QueueingTaskDispatcher.h b/orc-rt/include/orc-rt/QueueingTaskDispatcher.h
deleted file mode 100644
index d11b7fdf94248..0000000000000
--- a/orc-rt/include/orc-rt/QueueingTaskDispatcher.h
+++ /dev/null
@@ -1,73 +0,0 @@
-//===------------------ QueueingTaskDispatcher.h ----------------*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// QueueingTaskDispatcher class.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef ORC_RT_QUEUEINGTASKDISPATCHER_H
-#define ORC_RT_QUEUEINGTASKDISPATCHER_H
-
-#include "orc-rt/TaskDispatcher.h"
-
-#include <condition_variable>
-#include <deque>
-#include <memory>
-#include <mutex>
-
-namespace orc_rt {
-
-/// A TaskDispatcher implementation that puts tasks in a queue to be run.
-/// QueueingTaskDispatcher provides direct access to the queue, allowing
-/// clients to decide how to run tasks. It is intended for use on systems
-/// where threads are not available, and for unit tests.
-/// For most uses of the ORC runtime, use of QueueingTaskDispatcher is strongly
-/// discouraged, and alternatives like ThreadPoolTaskDispatcher are preferred.
-class QueueingTaskDispatcher : public TaskDispatcher {
-public:
- class TaskQueue {
- public:
- /// Append a task to the queue.
- void addTask(std::unique_ptr<Task> T);
-
- /// Shut down the queue. Further calls to addTask will be ignored (the task
- /// arguments will be discarded).
- void shutdown();
-
- /// Take the task most recently added to the queue. Blocks until a task is
- /// available or the dispatcher shuts down.
- std::unique_ptr<Task> takeLastIn();
-
- /// Take the earliest task from the queue. Blocks until a task is available
- /// or the dispatcher shuts down.
- std::unique_ptr<Task> takeFirstIn();
-
- /// Run tasks in last-in-first-out order until the queue is empty.
- void runLIFOUntilEmpty();
-
- /// Run tasks in first-in-first-out order until the queue is empty.
- void runFIFOUntilEmpty();
-
- private:
- std::mutex M;
- std::condition_variable CV;
- enum { Running, Shutdown } State = Running;
- std::deque<std::unique_ptr<Task>> Tasks;
- };
-
- QueueingTaskDispatcher(TaskQueue &Q) : Q(Q) {}
- void dispatch(std::unique_ptr<Task> T) override;
- void shutdown() override;
-
-private:
- TaskQueue &Q;
-};
-
-} // namespace orc_rt
-
-#endif // ORC_RT_QUEUEINGTASKDISPATCHER_H
diff --git a/orc-rt/include/orc-rt/Session.h b/orc-rt/include/orc-rt/Session.h
index b7c4ccffaa9a5..54f7bf5f96bf7 100644
--- a/orc-rt/include/orc-rt/Session.h
+++ b/orc-rt/include/orc-rt/Session.h
@@ -19,7 +19,6 @@
#include "orc-rt/LockedAccess.h"
#include "orc-rt/Service.h"
#include "orc-rt/SimpleSymbolTable.h"
-#include "orc-rt/TaskDispatcher.h"
#include "orc-rt/TaskGroup.h"
#include "orc-rt/WrapperFunction.h"
#include "orc-rt/move_only_function.h"
@@ -107,6 +106,18 @@ class Session {
using OnDetachFn = move_only_function<void()>;
using OnShutdownFn = move_only_function<void()>;
+ /// Callback used by the Session to run incoming wrapper-function calls.
+ ///
+ /// A ManagedCodeTaskGroup token is created for each call to this callback,
+ /// and implementations must eventually call either Fn (typically as
+ /// Fn(S, CallId, Return, ArgBytes.release())), or call Return directly to
+ /// bail out of the call (typically with
+ /// WrapperFunctionBuffer::createOutOfBandError(...)). Failing to do either
+ /// will block Session shutdown indefinitely.
+ using RunWrapperCall = move_only_function<void(
+ orc_rt_SessionRef S, uint64_t CallId, orc_rt_WrapperFunctionReturn Return,
+ orc_rt_WrapperFunction Fn, WrapperFunctionBuffer ArgBytes)>;
+
using HandlerTag = void *;
using OnCallHandlerCompleteFn =
move_only_function<void(WrapperFunctionBuffer)>;
@@ -208,9 +219,13 @@ class Session {
/// program are not generally visible to ORC-RT, but can optionally be
/// reported by calling the orc_rt_Session_reportError function.)
///
+ /// The RunCall callback will be invoked for every incoming wrapper-function
+ /// call, and is responsible for arranging the call to be run (inline,
+ /// queued, or posted to a thread pool, at the caller's discretion).
+ ///
/// Note that entry into the reporter is not synchronized: it may be
/// called from multiple threads concurrently.
- Session(ExecutorProcessInfo EPI, std::unique_ptr<TaskDispatcher> Dispatcher,
+ Session(ExecutorProcessInfo EPI, RunWrapperCall RunCall,
ErrorReporterFn ReportError);
// Sessions are not copyable or moveable.
@@ -229,9 +244,6 @@ class Session {
/// in.
const ExecutorProcessInfo &processInfo() const noexcept { return EPI; }
- /// Dispatch a task using the Session's TaskDispatcher.
- void dispatch(std::unique_ptr<Task> T) { Dispatcher->dispatch(std::move(T)); }
-
/// Report an error via the ErrorReporter function.
void reportError(Error Err) { ReportError(std::move(Err)); }
@@ -309,10 +321,8 @@ class Session {
/// complete (via ManagedCodeTaskGroup).
/// 3. Shutdown services: Calls onShutdown on all Services in reverse
/// order.
- /// 4. Shutdown TaskDispatcher.
///
- /// The optional OnShutdown callback is called after step (3), before
- /// the TaskDispatcher is shut down.
+ /// The optional OnShutdown callback is called after step (3).
void shutdown(OnShutdownFn OnShutdown = {});
/// Register a callback to be called when the Session detaches from the
@@ -464,9 +474,7 @@ class Session {
return;
}
- dispatch(makeGenericTask([=, ArgBytes = std::move(ArgBytes)]() mutable {
- Fn(wrap(this), CallId, wrapperReturn, ArgBytes.release());
- }));
+ RunCall(wrap(this), CallId, &wrapperReturn, Fn, std::move(ArgBytes));
}
void sendWrapperResult(uint64_t CallId, WrapperFunctionBuffer ResultBytes);
@@ -474,7 +482,7 @@ class Session {
orc_rt_WrapperFunctionBuffer ResultBytes);
ExecutorProcessInfo EPI;
- std::unique_ptr<TaskDispatcher> Dispatcher;
+ RunWrapperCall RunCall;
std::shared_ptr<TaskGroup> ManagedCodeTaskGroup = TaskGroup::Create();
std::shared_ptr<ControllerAccess> CA;
ErrorReporterFn ReportError;
diff --git a/orc-rt/include/orc-rt/TaskDispatcher.h b/orc-rt/include/orc-rt/TaskDispatcher.h
deleted file mode 100644
index f49d537ef25f7..0000000000000
--- a/orc-rt/include/orc-rt/TaskDispatcher.h
+++ /dev/null
@@ -1,64 +0,0 @@
-//===----------- TaskDispatcher.h - Task dispatch utils ---------*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Task and TaskDispatcher classes.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef ORC_RT_TASKDISPATCHER_H
-#define ORC_RT_TASKDISPATCHER_H
-
-#include "orc-rt/RTTI.h"
-
-#include <memory>
-#include <utility>
-
-namespace orc_rt {
-
-/// Represents an abstract task to be run.
-class Task : public RTTIExtends<Task, RTTIRoot> {
-public:
- virtual ~Task();
- virtual void run() = 0;
-};
-
-/// Base class for generic tasks.
-class GenericTask : public RTTIExtends<GenericTask, Task> {};
-
-/// Generic task implementation.
-template <typename FnT> class GenericTaskImpl : public GenericTask {
-public:
- GenericTaskImpl(FnT &&Fn) : Fn(std::forward<FnT>(Fn)) {}
- void run() override { Fn(); }
-
-private:
- FnT Fn;
-};
-
-/// Create a generic task from a function object.
-template <typename FnT> std::unique_ptr<GenericTask> makeGenericTask(FnT &&Fn) {
- return std::make_unique<GenericTaskImpl<std::decay_t<FnT>>>(
- std::forward<FnT>(Fn));
-}
-
-/// Abstract base for classes that dispatch Tasks.
-class TaskDispatcher {
-public:
- virtual ~TaskDispatcher();
-
- /// Run the given task.
- virtual void dispatch(std::unique_ptr<Task> T) = 0;
-
- /// Called by Session. Should cause further dispatches to be rejected, and
- /// wait until all previously dispatched tasks have completed.
- virtual void shutdown() = 0;
-};
-
-} // End namespace orc_rt
-
-#endif // ORC_RT_TASKDISPATCHER_H
diff --git a/orc-rt/include/orc-rt/ThreadPoolRunner.h b/orc-rt/include/orc-rt/ThreadPoolRunner.h
new file mode 100644
index 0000000000000..d9cd0ff01f067
--- /dev/null
+++ b/orc-rt/include/orc-rt/ThreadPoolRunner.h
@@ -0,0 +1,72 @@
+//===- ThreadPoolRunner.h -- Run wrapper calls in a thread pool -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// ThreadPoolRunner implementation.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef ORC_RT_THREADPOOLRUNNER_H
+#define ORC_RT_THREADPOOLRUNNER_H
+
+#include "orc-rt/WrapperFunction.h"
+#include "orc-rt/move_only_function.h"
+
+#include "orc-rt-c/CoreTypes.h"
+#include "orc-rt-c/WrapperFunction.h"
+
+#include <condition_variable>
+#include <cstddef>
+#include <cstdint>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+namespace orc_rt {
+
+/// A wrapper-call runner backed by a fixed-size pool of worker threads.
+///
+/// Each incoming call is enqueued onto an internal work queue and picked up
+/// by a worker thread.
+///
+/// Lifetime: the runner must outlive the Session that uses it. By the time
+/// the runner is destroyed the Session must have shut down — operator()
+/// after destruction begins is a contract violation (asserted). Any calls
+/// already pending in the queue at destruction time will be drained by the
+/// workers before they exit.
+class ThreadPoolRunner {
+public:
+ ThreadPoolRunner(size_t NumThreads);
+ ~ThreadPoolRunner();
+
+ ThreadPoolRunner(const ThreadPoolRunner &) = delete;
+ ThreadPoolRunner &operator=(const ThreadPoolRunner &) = delete;
+ ThreadPoolRunner(ThreadPoolRunner &&) = delete;
+ ThreadPoolRunner &operator=(ThreadPoolRunner &&) = delete;
+
+ /// Enqueue a wrapper-function call to be run by a worker thread. Must not
+ /// be called once destruction has begun.
+ void operator()(orc_rt_SessionRef S, uint64_t CallId,
+ orc_rt_WrapperFunctionReturn Return,
+ orc_rt_WrapperFunction Fn, WrapperFunctionBuffer ArgBytes);
+
+private:
+ void workerLoop();
+
+ std::vector<std::thread> Workers;
+
+ std::mutex M;
+ std::condition_variable CV;
+ /// Set by the destructor. Stops new dispatches (asserted in operator())
+ /// and tells worker threads to exit once they've drained Pending.
+ bool Stop = false;
+ std::vector<move_only_function<void()>> Pending;
+};
+
+} // namespace orc_rt
+
+#endif // ORC_RT_THREADPOOLRUNNER_H
diff --git a/orc-rt/include/orc-rt/ThreadPoolTaskDispatcher.h b/orc-rt/include/orc-rt/ThreadPoolTaskDispatcher.h
deleted file mode 100644
index 227c3500a1321..0000000000000
--- a/orc-rt/include/orc-rt/ThreadPoolTaskDispatcher.h
+++ /dev/null
@@ -1,48 +0,0 @@
-//===--- ThreadPoolTaskDispatcher.h - Run tasks in thread pool --*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// ThreadPoolTaskDispatcher implementation.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef ORC_RT_THREADPOOLTASKDISPATCHER_H
-#define ORC_RT_THREADPOOLTASKDISPATCHER_H
-
-#include "orc-rt/TaskDispatcher.h"
-
-#include <condition_variable>
-#include <mutex>
-#include <thread>
-#include <vector>
-
-namespace orc_rt {
-
-/// Thread-pool based TaskDispatcher.
-///
-/// Will spawn NumThreads threads to run dispatched Tasks.
-class ThreadPoolTaskDispatcher : public TaskDispatcher {
-public:
- ThreadPoolTaskDispatcher(size_t NumThreads);
- ~ThreadPoolTaskDispatcher() override;
- void dispatch(std::unique_ptr<Task> T) override;
- void shutdown() override;
-
-private:
- void taskLoop();
-
- std::vector<std::thread> Threads;
-
- std::mutex M;
- bool AcceptingTasks = true;
- std::condition_variable CV;
- std::vector<std::unique_ptr<Task>> PendingTasks;
-};
-
-} // End namespace orc_rt
-
-#endif // ORC_RT_THREADPOOLTASKDISPATCHER_H
diff --git a/orc-rt/lib/executor/CMakeLists.txt b/orc-rt/lib/executor/CMakeLists.txt
index 8a4168f354952..5f2a70b2b53e2 100644
--- a/orc-rt/lib/executor/CMakeLists.txt
+++ b/orc-rt/lib/executor/CMakeLists.txt
@@ -5,13 +5,11 @@ set(files
Error.cpp
ExecutorProcessInfo.cpp
NativeDylibManager.cpp
- QueueingTaskDispatcher.cpp
RTTI.cpp
Service.cpp
Session.cpp
SimpleNativeMemoryMap.cpp
- TaskDispatcher.cpp
- ThreadPoolTaskDispatcher.cpp
+ ThreadPoolRunner.cpp
sps-ci/AllSPSCI.cpp
sps-ci/CallSPSCI.cpp
sps-ci/MemoryAccessSPSCI.cpp
diff --git a/orc-rt/lib/executor/QueueingTaskDispatcher.cpp b/orc-rt/lib/executor/QueueingTaskDispatcher.cpp
deleted file mode 100644
index 65d862bfccfda..0000000000000
--- a/orc-rt/lib/executor/QueueingTaskDispatcher.cpp
+++ /dev/null
@@ -1,73 +0,0 @@
-//===- QueueingTaskDispatcher.cpp -----------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Contains the implementation of APIs in the orc-rt/QueueingTaskDispatcher.h
-// header.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/QueueingTaskDispatcher.h"
-
-#include <cassert>
-
-namespace orc_rt {
-
-void QueueingTaskDispatcher::TaskQueue::addTask(std::unique_ptr<Task> T) {
- {
- std::scoped_lock<std::mutex> Lock(M);
- if (State == Running)
- Tasks.push_back(std::move(T));
- }
- CV.notify_one();
-}
-
-void QueueingTaskDispatcher::TaskQueue::shutdown() {
- {
- std::scoped_lock<std::mutex> Lock(M);
- State = Shutdown;
- }
- CV.notify_all();
-}
-
-std::unique_ptr<Task> QueueingTaskDispatcher::TaskQueue::takeLastIn() {
- std::unique_lock<std::mutex> Lock(M);
- CV.wait(Lock, [&]() { return !Tasks.empty() || State == Shutdown; });
- if (Tasks.empty())
- return nullptr;
- auto T = std::move(Tasks.back());
- Tasks.pop_back();
- return T;
-}
-
-std::unique_ptr<Task> QueueingTaskDispatcher::TaskQueue::takeFirstIn() {
- std::unique_lock<std::mutex> Lock(M);
- CV.wait(Lock, [&]() { return !Tasks.empty() || State == Shutdown; });
- if (Tasks.empty())
- return nullptr;
- auto T = std::move(Tasks.front());
- Tasks.pop_front();
- return T;
-}
-
-void QueueingTaskDispatcher::TaskQueue::runLIFOUntilEmpty() {
- while (auto T = takeLastIn())
- T->run();
-}
-
-void QueueingTaskDispatcher::TaskQueue::runFIFOUntilEmpty() {
- while (auto T = takeFirstIn())
- T->run();
-}
-
-void QueueingTaskDispatcher::dispatch(std::unique_ptr<Task> T) {
- Q.addTask(std::move(T));
-}
-
-void QueueingTaskDispatcher::shutdown() { Q.shutdown(); }
-
-} // namespace orc_rt
diff --git a/orc-rt/lib/executor/Session.cpp b/orc-rt/lib/executor/Session.cpp
index ec913010d818e..d153c55cea1be 100644
--- a/orc-rt/lib/executor/Session.cpp
+++ b/orc-rt/lib/executor/Session.cpp
@@ -49,10 +49,9 @@ class Session::NotificationService : public Service {
Session::ControllerAccess::~ControllerAccess() = default;
-Session::Session(ExecutorProcessInfo EPI,
- std::unique_ptr<TaskDispatcher> Dispatcher,
+Session::Session(ExecutorProcessInfo EPI, RunWrapperCall RunCall,
ErrorReporterFn ReportError)
- : EPI(std::move(EPI)), Dispatcher(std::move(Dispatcher)),
+ : EPI(std::move(EPI)), RunCall(std::move(RunCall)),
ReportError(std::move(ReportError)),
Notifiers(createService<NotificationService>()) {}
@@ -350,8 +349,6 @@ void Session::shutdownServices(std::vector<Service *> ToNotify) {
}
void Session::completeShutdown() {
- Dispatcher->shutdown();
-
{
std::scoped_lock<std::mutex> Lock(M);
assert(CurrentState == State::Shutdown);
diff --git a/orc-rt/lib/executor/TaskDispatcher.cpp b/orc-rt/lib/executor/TaskDispatcher.cpp
deleted file mode 100644
index 9e42a66c2ea94..0000000000000
--- a/orc-rt/lib/executor/TaskDispatcher.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-//===- TaskDispatcher.cpp -------------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Contains the implementation of APIs in the orc-rt/TaskDispatcher.h header.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/TaskDispatcher.h"
-
-namespace orc_rt {
-
-Task::~Task() = default;
-TaskDispatcher::~TaskDispatcher() = default;
-
-} // namespace orc_rt
diff --git a/orc-rt/lib/executor/ThreadPoolRunner.cpp b/orc-rt/lib/executor/ThreadPoolRunner.cpp
new file mode 100644
index 0000000000000..fea3cd60eda58
--- /dev/null
+++ b/orc-rt/lib/executor/ThreadPoolRunner.cpp
@@ -0,0 +1,69 @@
+//===- ThreadPoolRunner.cpp -----------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Contains the implementation of APIs in the orc-rt/ThreadPoolRunner.h
+// header.
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt/ThreadPoolRunner.h"
+
+#include <cassert>
+
+namespace orc_rt {
+
+ThreadPoolRunner::ThreadPoolRunner(size_t NumThreads) {
+ Workers.reserve(NumThreads);
+ for (size_t I = 0; I < NumThreads; ++I)
+ Workers.emplace_back([this]() { workerLoop(); });
+}
+
+ThreadPoolRunner::~ThreadPoolRunner() {
+ {
+ std::scoped_lock<std::mutex> Lock(M);
+ Stop = true;
+ }
+ CV.notify_all();
+ for (auto &Worker : Workers)
+ Worker.join();
+}
+
+void ThreadPoolRunner::operator()(orc_rt_SessionRef S, uint64_t CallId,
+ orc_rt_WrapperFunctionReturn Return,
+ orc_rt_WrapperFunction Fn,
+ WrapperFunctionBuffer ArgBytes) {
+ {
+ std::scoped_lock<std::mutex> Lock(M);
+ assert(!Stop &&
+ "operator() called on ThreadPoolRunner after destruction begun");
+ Pending.push_back([=, ArgBytes = std::move(ArgBytes)]() mutable {
+ Fn(S, CallId, Return, ArgBytes.release());
+ });
+ }
+ CV.notify_one();
+}
+
+void ThreadPoolRunner::workerLoop() {
+ while (true) {
+ move_only_function<void()> Call;
+ {
+ std::unique_lock<std::mutex> Lock(M);
+ CV.wait(Lock, [this]() { return !Pending.empty() || Stop; });
+
+ if (Pending.empty() && Stop)
+ return;
+
+ Call = std::move(Pending.back());
+ Pending.pop_back();
+ }
+
+ Call();
+ }
+}
+
+} // namespace orc_rt
diff --git a/orc-rt/lib/executor/ThreadPoolTaskDispatcher.cpp b/orc-rt/lib/executor/ThreadPoolTaskDispatcher.cpp
deleted file mode 100644
index 4bf7e5df69654..0000000000000
--- a/orc-rt/lib/executor/ThreadPoolTaskDispatcher.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-//===- ThreadPoolTaskDispatcher.cpp ---------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Contains the implementation of APIs in the orc-rt/ThreadPoolTaskDispatcher.h
-// header.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/ThreadPoolTaskDispatcher.h"
-
-#include <cassert>
-
-namespace orc_rt {
-
-ThreadPoolTaskDispatcher::~ThreadPoolTaskDispatcher() {
- assert(!AcceptingTasks && "shutdown was not run");
-}
-
-ThreadPoolTaskDispatcher::ThreadPoolTaskDispatcher(size_t NumThreads) {
- Threads.reserve(NumThreads);
- for (size_t I = 0; I < NumThreads; ++I)
- Threads.emplace_back([this]() { taskLoop(); });
-}
-
-void ThreadPoolTaskDispatcher::dispatch(std::unique_ptr<Task> T) {
- {
- std::scoped_lock<std::mutex> Lock(M);
- if (!AcceptingTasks)
- return;
- PendingTasks.push_back(std::move(T));
- }
- CV.notify_one();
-}
-
-void ThreadPoolTaskDispatcher::shutdown() {
- {
- std::scoped_lock<std::mutex> Lock(M);
- assert(AcceptingTasks && "ThreadPoolTaskDispatcher already shut down?");
- AcceptingTasks = false;
- }
- CV.notify_all();
- for (auto &Thread : Threads)
- Thread.join();
-}
-
-void ThreadPoolTaskDispatcher::taskLoop() {
- while (true) {
- std::unique_ptr<Task> T;
- {
- std::unique_lock<std::mutex> Lock(M);
- CV.wait(Lock,
- [this]() { return !PendingTasks.empty() || !AcceptingTasks; });
-
- if (!AcceptingTasks && PendingTasks.empty())
- return;
-
- T = std::move(PendingTasks.back());
- PendingTasks.pop_back();
- }
-
- T->run();
- }
-}
-
-} // namespace orc_rt
diff --git a/orc-rt/unittests/BootstrapInfoTest.cpp b/orc-rt/unittests/BootstrapInfoTest.cpp
index f38626e2bc434..9d409c7c0c5ff 100644
--- a/orc-rt/unittests/BootstrapInfoTest.cpp
+++ b/orc-rt/unittests/BootstrapInfoTest.cpp
@@ -12,7 +12,7 @@
#include "orc-rt/BootstrapInfo.h"
#include "orc-rt/Session.h"
-#include "orc-rt/TaskDispatcher.h"
+#include "orc-rt/move_only_function.h"
#include "gtest/gtest.h"
#include "CommonTestUtils.h"
@@ -20,8 +20,7 @@
using namespace orc_rt;
TEST(BootstrapInfoTest, ExplicitConstruction) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
BootstrapInfo BI(S);
EXPECT_EQ(&BI.session(), &S);
EXPECT_TRUE(BI.symbols().empty());
@@ -29,8 +28,7 @@ TEST(BootstrapInfoTest, ExplicitConstruction) {
}
TEST(BootstrapInfoTest, ExplicitConstructionWithSymbolsAndValues) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
int X = 0;
SimpleSymbolTable Symbols;
std::pair<const char *, void *> Syms[] = {{"orc_rt_X", &X}};
@@ -48,22 +46,19 @@ TEST(BootstrapInfoTest, ExplicitConstructionWithSymbolsAndValues) {
}
TEST(BootstrapInfoTest, ProcessInfoDelegates) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
BootstrapInfo BI(S);
EXPECT_EQ(&BI.processInfo(), &S.processInfo());
}
TEST(BootstrapInfoTest, CreateDefaultSucceeds) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
auto BI = cantFail(BootstrapInfo::CreateDefault(S));
EXPECT_EQ(&BI.session(), &S);
}
TEST(BootstrapInfoTest, CreateDefaultContainsSessionSymbol) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
auto BI = cantFail(BootstrapInfo::CreateDefault(S));
ASSERT_TRUE(BI.symbols().count("orc_rt_Session_Instance"));
EXPECT_EQ(BI.symbols().at("orc_rt_Session_Instance"),
@@ -71,8 +66,7 @@ TEST(BootstrapInfoTest, CreateDefaultContainsSessionSymbol) {
}
TEST(BootstrapInfoTest, CreateDefaultContainsSPSCISymbols) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
auto BI = cantFail(BootstrapInfo::CreateDefault(S));
// The default addAll should have registered SPS CI symbols.
EXPECT_TRUE(
@@ -80,8 +74,7 @@ TEST(BootstrapInfoTest, CreateDefaultContainsSPSCISymbols) {
}
TEST(BootstrapInfoTest, CreateDefaultWithNoSymbolsBuilder) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
auto BI = cantFail(BootstrapInfo::CreateDefault(S, /*AddInitialSymbols=*/{},
/*AddInitialValues=*/{}));
// Should still contain the session symbol (added unconditionally).
@@ -92,8 +85,7 @@ TEST(BootstrapInfoTest, CreateDefaultWithNoSymbolsBuilder) {
}
TEST(BootstrapInfoTest, CreateDefaultWithCustomValuesBuilder) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
auto BI = cantFail(BootstrapInfo::CreateDefault(
S, sps_ci::addAll, [](BootstrapInfo::ValueMap &Values) -> Error {
Values["test_key"] = "test_value";
@@ -103,8 +95,7 @@ TEST(BootstrapInfoTest, CreateDefaultWithCustomValuesBuilder) {
}
TEST(BootstrapInfoTest, CreateDefaultSymbolsBuilderError) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
auto BI = BootstrapInfo::CreateDefault(S, [](SimpleSymbolTable &) -> Error {
return make_error<StringError>("symbols builder failed");
});
@@ -114,8 +105,7 @@ TEST(BootstrapInfoTest, CreateDefaultSymbolsBuilderError) {
}
TEST(BootstrapInfoTest, CreateDefaultValuesBuilderError) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
auto BI = BootstrapInfo::CreateDefault(
S, sps_ci::addAll, [](BootstrapInfo::ValueMap &) -> Error {
return make_error<StringError>("values builder failed");
@@ -126,8 +116,7 @@ TEST(BootstrapInfoTest, CreateDefaultValuesBuilderError) {
}
TEST(BootstrapInfoTest, MutableSymbolsAndValues) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
BootstrapInfo BI(S);
int X = 0;
diff --git a/orc-rt/unittests/CMakeLists.txt b/orc-rt/unittests/CMakeLists.txt
index 0bce4382f250f..6634f4cb402e2 100644
--- a/orc-rt/unittests/CMakeLists.txt
+++ b/orc-rt/unittests/CMakeLists.txt
@@ -32,7 +32,7 @@ add_orc_rt_unittest(CoreTests
MemoryFlagsTest.cpp
NativeDylibManagerTest.cpp
NativeDylibManagerSPSCITest.cpp
- QueueingTaskDispatcherTest.cpp
+ QueueingRunnerTest.cpp
RTTITest.cpp
ScopeExitTest.cpp
SessionTest.cpp
@@ -44,7 +44,7 @@ add_orc_rt_unittest(CoreTests
SPSWrapperFunctionTest.cpp
SPSWrapperFunctionBufferTest.cpp
TaskGroupTest.cpp
- ThreadPoolTaskDispatcherTest.cpp
+ ThreadPoolRunnerTest.cpp
WrapperFunctionBufferTest.cpp
bind-test.cpp
bit-test.cpp
diff --git a/orc-rt/unittests/CommonTestUtils.h b/orc-rt/unittests/CommonTestUtils.h
index e0ec3442f743b..4d584627fa6d6 100644
--- a/orc-rt/unittests/CommonTestUtils.h
+++ b/orc-rt/unittests/CommonTestUtils.h
@@ -11,10 +11,15 @@
#include "orc-rt/Error.h"
#include "orc-rt/ExecutorProcessInfo.h"
-#include "orc-rt/TaskDispatcher.h"
+#include "orc-rt/WrapperFunction.h"
#include "orc-rt/move_only_function.h"
+#include "orc-rt-c/CoreTypes.h"
+#include "orc-rt-c/WrapperFunction.h"
+
+#include <cassert>
#include <cstddef>
+#include <cstdint>
#include <future>
inline void noErrors(orc_rt::Error Err) { orc_rt::cantFail(std::move(Err)); }
@@ -23,13 +28,13 @@ inline orc_rt::ExecutorProcessInfo mockExecutorProcessInfo() noexcept {
return orc_rt::ExecutorProcessInfo("arm64-apple-darwin", 16384);
}
-class NoDispatcher : public orc_rt::TaskDispatcher {
-public:
- void dispatch(std::unique_ptr<orc_rt::Task> T) override {
- assert(false && "strictly no dispatching!");
- }
- void shutdown() override {}
-};
+/// RunWrapperCall callback for tests that should never dispatch a wrapper
+/// call. Asserts on invocation.
+inline void noDispatch(orc_rt_SessionRef, uint64_t,
+ orc_rt_WrapperFunctionReturn, orc_rt_WrapperFunction,
+ orc_rt::WrapperFunctionBuffer) {
+ assert(false && "strictly no dispatching!");
+}
template <size_t Idx = 0> class OpCounter {
public:
diff --git a/orc-rt/unittests/NativeDylibManagerSPSCITest.cpp b/orc-rt/unittests/NativeDylibManagerSPSCITest.cpp
index 7ecda766ef01f..59f32b6c5abaa 100644
--- a/orc-rt/unittests/NativeDylibManagerSPSCITest.cpp
+++ b/orc-rt/unittests/NativeDylibManagerSPSCITest.cpp
@@ -75,8 +75,8 @@ constexpr auto Weak = NativeDylibManager::WeaklyReferencedSymbol;
class NativeDylibManagerSPSCITest : public ::testing::Test {
protected:
void SetUp() override {
- S = std::make_unique<Session>(mockExecutorProcessInfo(),
- std::make_unique<NoDispatcher>(), noErrors);
+ S = std::make_unique<Session>(mockExecutorProcessInfo(), noDispatch,
+ noErrors);
NDM = cantFail(NativeDylibManager::Create(*S, CI));
}
diff --git a/orc-rt/unittests/NativeDylibManagerTest.cpp b/orc-rt/unittests/NativeDylibManagerTest.cpp
index 367b8b8600834..a3c0344c8eff6 100644
--- a/orc-rt/unittests/NativeDylibManagerTest.cpp
+++ b/orc-rt/unittests/NativeDylibManagerTest.cpp
@@ -62,16 +62,14 @@ syncLookup(NativeDylibManager &NDM, void *Handle,
}
TEST(NativeDylibManagerTest, Create) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ST;
auto NDM = NativeDylibManager::Create(S, ST);
ASSERT_TRUE(!!NDM) << toString(NDM.takeError());
}
TEST(NativeDylibManagerTest, Load) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ST;
auto NDM = cantFail(NativeDylibManager::Create(S, ST));
@@ -81,8 +79,7 @@ TEST(NativeDylibManagerTest, Load) {
}
TEST(NativeDylibManagerTest, LoadNonExistent) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ST;
auto NDM = cantFail(NativeDylibManager::Create(S, ST));
@@ -92,8 +89,7 @@ TEST(NativeDylibManagerTest, LoadNonExistent) {
}
TEST(NativeDylibManagerTest, LoadEmptyPathReturnsGlobalHandle) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ST;
auto NDM = cantFail(NativeDylibManager::Create(S, ST));
@@ -112,8 +108,7 @@ TEST(NativeDylibManagerTest, LoadEmptyPathReturnsGlobalHandle) {
}
TEST(NativeDylibManagerTest, LookupSingleSymbol) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ST;
auto NDM = cantFail(NativeDylibManager::Create(S, ST));
@@ -132,8 +127,7 @@ TEST(NativeDylibManagerTest, LookupSingleSymbol) {
}
TEST(NativeDylibManagerTest, LookupMultipleSymbols) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ST;
auto NDM = cantFail(NativeDylibManager::Create(S, ST));
@@ -156,8 +150,7 @@ TEST(NativeDylibManagerTest, LookupMultipleSymbols) {
}
TEST(NativeDylibManagerTest, LookupWeakMissingSymbol) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ST;
auto NDM = cantFail(NativeDylibManager::Create(S, ST));
@@ -172,8 +165,7 @@ TEST(NativeDylibManagerTest, LookupWeakMissingSymbol) {
}
TEST(NativeDylibManagerTest, LookupRequiredMissingSymbol) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ST;
auto NDM = cantFail(NativeDylibManager::Create(S, ST));
@@ -187,8 +179,7 @@ TEST(NativeDylibManagerTest, LookupRequiredMissingSymbol) {
}
TEST(NativeDylibManagerTest, LookupMixedRequiredAndWeak) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ST;
auto NDM = cantFail(NativeDylibManager::Create(S, ST));
diff --git a/orc-rt/unittests/QueueingRunnerTest.cpp b/orc-rt/unittests/QueueingRunnerTest.cpp
new file mode 100644
index 0000000000000..06e32676f5959
--- /dev/null
+++ b/orc-rt/unittests/QueueingRunnerTest.cpp
@@ -0,0 +1,133 @@
+//===- QueueingRunnerTest.cpp ---------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt/QueueingRunner.h"
+#include "orc-rt/move_only_function.h"
+#include "gtest/gtest.h"
+
+#include <cstdint>
+#include <deque>
+#include <vector>
+
+using namespace orc_rt;
+
+namespace {
+
+using TaskQueue = std::deque<move_only_function<void()>>;
+
+// A dummy SessionRef value used purely to thread an opaque pointer through
+// the runner's enqueue path.
+inline orc_rt_SessionRef dummySession() noexcept {
+ return reinterpret_cast<orc_rt_SessionRef>(uintptr_t{0xABCD});
+}
+
+inline orc_rt_WrapperFunctionReturn dummyReturn() noexcept {
+ return [](orc_rt_SessionRef, uint64_t, orc_rt_WrapperFunctionBuffer) {};
+}
+
+// Test wrapper-function that records each invocation in a globally-accessible
+// log via its CallId.
+struct CallRecord {
+ orc_rt_SessionRef Session;
+ uint64_t CallId;
+};
+
+static std::vector<CallRecord> *RecordingLog = nullptr;
+
+static void recordingFn(orc_rt_SessionRef S, uint64_t CallId,
+ orc_rt_WrapperFunctionReturn,
+ orc_rt_WrapperFunctionBuffer ArgBytes) {
+ WrapperFunctionBuffer Owned(ArgBytes);
+ RecordingLog->push_back({S, CallId});
+}
+
+class QueueingRunnerTest : public ::testing::Test {
+protected:
+ void SetUp() override { RecordingLog = &Log; }
+ void TearDown() override { RecordingLog = nullptr; }
+
+ std::vector<CallRecord> Log;
+ TaskQueue Q;
+};
+
+TEST_F(QueueingRunnerTest, EnqueueDoesNotRunImmediately) {
+ QueueingRunner R(Q);
+ R(dummySession(), /*CallId=*/0, dummyReturn(), recordingFn,
+ WrapperFunctionBuffer());
+ EXPECT_EQ(Log.size(), 0u) << "Enqueue should not run the call";
+ EXPECT_EQ(Q.size(), 1u) << "Call should be sitting in the queue";
+}
+
+TEST_F(QueueingRunnerTest, RunFIFOUntilEmpty) {
+ QueueingRunner R(Q);
+ for (uint64_t I = 0; I < 3; ++I)
+ R(dummySession(), I, dummyReturn(), recordingFn, WrapperFunctionBuffer());
+
+ QueueingRunner<TaskQueue>::runFIFOUntilEmpty(Q);
+
+ ASSERT_EQ(Log.size(), 3u);
+ EXPECT_EQ(Log[0].CallId, 0u);
+ EXPECT_EQ(Log[1].CallId, 1u);
+ EXPECT_EQ(Log[2].CallId, 2u);
+ EXPECT_TRUE(Q.empty());
+}
+
+TEST_F(QueueingRunnerTest, RunLIFOUntilEmpty) {
+ QueueingRunner R(Q);
+ for (uint64_t I = 0; I < 3; ++I)
+ R(dummySession(), I, dummyReturn(), recordingFn, WrapperFunctionBuffer());
+
+ QueueingRunner<TaskQueue>::runLIFOUntilEmpty(Q);
+
+ ASSERT_EQ(Log.size(), 3u);
+ EXPECT_EQ(Log[0].CallId, 2u);
+ EXPECT_EQ(Log[1].CallId, 1u);
+ EXPECT_EQ(Log[2].CallId, 0u);
+ EXPECT_TRUE(Q.empty());
+}
+
+TEST_F(QueueingRunnerTest, DrainOnEmptyQueueIsNoOp) {
+ // Both drain helpers should return immediately on an empty queue rather
+ // than blocking.
+ QueueingRunner<TaskQueue>::runFIFOUntilEmpty(Q);
+ QueueingRunner<TaskQueue>::runLIFOUntilEmpty(Q);
+ EXPECT_EQ(Log.size(), 0u);
+}
+
+TEST_F(QueueingRunnerTest, DrainPicksUpCallsEnqueuedDuringDrain) {
+ // A call enqueued by a running call should also be drained in the same
+ // runFIFOUntilEmpty call.
+ QueueingRunner R(Q);
+
+ // First call enqueues a second call from inside its body. We use a custom
+ // wrapper-function (not recordingFn) to do that, since recordingFn doesn't
+ // know about the queue.
+ static QueueingRunner<TaskQueue> *PendingR = nullptr;
+ PendingR = &R;
+ static auto reentrantFn = [](orc_rt_SessionRef S, uint64_t CallId,
+ orc_rt_WrapperFunctionReturn,
+ orc_rt_WrapperFunctionBuffer ArgBytes) {
+ WrapperFunctionBuffer Owned(ArgBytes);
+ RecordingLog->push_back({S, CallId});
+ if (CallId == 0)
+ (*PendingR)(S, /*CallId=*/1, dummyReturn(), recordingFn,
+ WrapperFunctionBuffer());
+ };
+
+ R(dummySession(), /*CallId=*/0, dummyReturn(), reentrantFn,
+ WrapperFunctionBuffer());
+
+ QueueingRunner<TaskQueue>::runFIFOUntilEmpty(Q);
+
+ ASSERT_EQ(Log.size(), 2u);
+ EXPECT_EQ(Log[0].CallId, 0u);
+ EXPECT_EQ(Log[1].CallId, 1u);
+ PendingR = nullptr;
+}
+
+} // end anonymous namespace
diff --git a/orc-rt/unittests/QueueingTaskDispatcherTest.cpp b/orc-rt/unittests/QueueingTaskDispatcherTest.cpp
deleted file mode 100644
index 06d0347b444cd..0000000000000
--- a/orc-rt/unittests/QueueingTaskDispatcherTest.cpp
+++ /dev/null
@@ -1,291 +0,0 @@
-//===- QueueingTaskDispatcherTest.cpp -------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/QueueingTaskDispatcher.h"
-#include "gtest/gtest.h"
-
-#include <atomic>
-#include <memory>
-#include <thread>
-#include <vector>
-
-using namespace orc_rt;
-
-namespace {
-
-TEST(QueueingTaskDispatcherTest, BasicTaskDispatch) {
- // Test basic task dispatching and retrieval.
- QueueingTaskDispatcher::TaskQueue Q;
- QueueingTaskDispatcher Dispatcher(Q);
- bool TaskRan = false;
-
- Dispatcher.dispatch(makeGenericTask([&]() { TaskRan = true; }));
- Dispatcher.shutdown();
-
- auto Task = Q.takeFirstIn();
- EXPECT_NE(Task, nullptr);
- Task->run();
- EXPECT_TRUE(TaskRan);
-
- // Queue is shut down and drained — should return nullptr.
- EXPECT_EQ(Q.takeFirstIn(), nullptr);
-}
-
-TEST(QueueingTaskDispatcherTest, MultipleTasks) {
- // Test dispatching and running multiple tasks.
- QueueingTaskDispatcher::TaskQueue Q;
- QueueingTaskDispatcher Dispatcher(Q);
- int TaskCount = 0;
- constexpr int NumTasks = 5;
-
- for (int I = 0; I < NumTasks; ++I)
- Dispatcher.dispatch(makeGenericTask([&]() { ++TaskCount; }));
- Dispatcher.shutdown();
-
- // Take and run all tasks.
- for (int I = 0; I < NumTasks; ++I) {
- auto Task = Q.takeFirstIn();
- EXPECT_NE(Task, nullptr);
- Task->run();
- }
-
- EXPECT_EQ(TaskCount, NumTasks);
- EXPECT_EQ(Q.takeFirstIn(), nullptr);
-}
-
-TEST(QueueingTaskDispatcherTest, TakeLastInLIFOOrder) {
- // Test that takeLastIn retrieves tasks in LIFO order.
- QueueingTaskDispatcher::TaskQueue Q;
- QueueingTaskDispatcher Dispatcher(Q);
- std::vector<int> ExecutionOrder;
-
- for (int I = 0; I < 3; ++I)
- Dispatcher.dispatch(makeGenericTask(
- [&ExecutionOrder, I]() { ExecutionOrder.push_back(I); }));
- Dispatcher.shutdown();
-
- while (auto Task = Q.takeLastIn())
- Task->run();
-
- ASSERT_EQ(ExecutionOrder.size(), 3u);
- EXPECT_EQ(ExecutionOrder[0], 2);
- EXPECT_EQ(ExecutionOrder[1], 1);
- EXPECT_EQ(ExecutionOrder[2], 0);
-}
-
-TEST(QueueingTaskDispatcherTest, TakeFirstInFIFOOrder) {
- // Test that takeFirstIn retrieves tasks in FIFO order.
- QueueingTaskDispatcher::TaskQueue Q;
- QueueingTaskDispatcher Dispatcher(Q);
- std::vector<int> ExecutionOrder;
-
- for (int I = 0; I < 3; ++I)
- Dispatcher.dispatch(makeGenericTask(
- [&ExecutionOrder, I]() { ExecutionOrder.push_back(I); }));
- Dispatcher.shutdown();
-
- while (auto Task = Q.takeFirstIn())
- Task->run();
-
- ASSERT_EQ(ExecutionOrder.size(), 3u);
- EXPECT_EQ(ExecutionOrder[0], 0);
- EXPECT_EQ(ExecutionOrder[1], 1);
- EXPECT_EQ(ExecutionOrder[2], 2);
-}
-
-TEST(QueueingTaskDispatcherTest, RunLIFOUntilEmpty) {
- // Test the runLIFOUntilEmpty convenience method.
- QueueingTaskDispatcher::TaskQueue Q;
- QueueingTaskDispatcher Dispatcher(Q);
- std::vector<int> ExecutionOrder;
-
- for (int I = 0; I < 3; ++I)
- Dispatcher.dispatch(makeGenericTask(
- [&ExecutionOrder, I]() { ExecutionOrder.push_back(I); }));
- Dispatcher.shutdown();
-
- Q.runLIFOUntilEmpty();
-
- ASSERT_EQ(ExecutionOrder.size(), 3u);
- EXPECT_EQ(ExecutionOrder[0], 2);
- EXPECT_EQ(ExecutionOrder[1], 1);
- EXPECT_EQ(ExecutionOrder[2], 0);
-}
-
-TEST(QueueingTaskDispatcherTest, RunFIFOUntilEmpty) {
- // Test the runFIFOUntilEmpty convenience method.
- QueueingTaskDispatcher::TaskQueue Q;
- QueueingTaskDispatcher Dispatcher(Q);
- std::vector<int> ExecutionOrder;
-
- for (int I = 0; I < 3; ++I)
- Dispatcher.dispatch(makeGenericTask(
- [&ExecutionOrder, I]() { ExecutionOrder.push_back(I); }));
- Dispatcher.shutdown();
-
- Q.runFIFOUntilEmpty();
-
- ASSERT_EQ(ExecutionOrder.size(), 3u);
- EXPECT_EQ(ExecutionOrder[0], 0);
- EXPECT_EQ(ExecutionOrder[1], 1);
- EXPECT_EQ(ExecutionOrder[2], 2);
-}
-
-TEST(QueueingTaskDispatcherTest, MixedTakeOperations) {
- // Test mixing takeFirstIn and takeLastIn.
- QueueingTaskDispatcher::TaskQueue Q;
- QueueingTaskDispatcher Dispatcher(Q);
- std::vector<int> ExecutionOrder;
-
- // Dispatch tasks 0, 1, 2.
- for (int I = 0; I < 3; ++I)
- Dispatcher.dispatch(makeGenericTask(
- [&ExecutionOrder, I]() { ExecutionOrder.push_back(I); }));
- Dispatcher.shutdown();
-
- // takeLastIn should get task 2.
- auto Task1 = Q.takeLastIn();
- ASSERT_NE(Task1, nullptr);
- Task1->run();
-
- // takeFirstIn should get task 0.
- auto Task2 = Q.takeFirstIn();
- ASSERT_NE(Task2, nullptr);
- Task2->run();
-
- // takeLastIn should get task 1 (only one left).
- auto Task3 = Q.takeLastIn();
- ASSERT_NE(Task3, nullptr);
- Task3->run();
-
- EXPECT_EQ(Q.takeFirstIn(), nullptr);
-
- ASSERT_EQ(ExecutionOrder.size(), 3u);
- EXPECT_EQ(ExecutionOrder[0], 2);
- EXPECT_EQ(ExecutionOrder[1], 0);
- EXPECT_EQ(ExecutionOrder[2], 1);
-}
-
-TEST(QueueingTaskDispatcherTest, ShutdownDrainsRemainingTasks) {
- // Verify that tasks dispatched before shutdown can still be taken.
- QueueingTaskDispatcher::TaskQueue Q;
- QueueingTaskDispatcher Dispatcher(Q);
- int TaskCount = 0;
-
- for (int I = 0; I < 3; ++I)
- Dispatcher.dispatch(makeGenericTask([&]() { ++TaskCount; }));
-
- Dispatcher.shutdown();
-
- // All pre-shutdown tasks should still be available.
- while (auto Task = Q.takeFirstIn())
- Task->run();
-
- EXPECT_EQ(TaskCount, 3);
-}
-
-TEST(QueueingTaskDispatcherTest, DispatchAfterShutdown) {
- // Tasks dispatched after shutdown should be discarded.
- QueueingTaskDispatcher::TaskQueue Q;
- QueueingTaskDispatcher Dispatcher(Q);
- bool TaskRan = false;
-
- Dispatcher.shutdown();
-
- Dispatcher.dispatch(makeGenericTask([&]() { TaskRan = true; }));
-
- EXPECT_EQ(Q.takeFirstIn(), nullptr);
- EXPECT_FALSE(TaskRan);
-}
-
-TEST(QueueingTaskDispatcherTest, TakeBlocksUntilTaskAvailable) {
- // Verify that takeFirstIn blocks on an empty queue until a task arrives.
- QueueingTaskDispatcher::TaskQueue Q;
- QueueingTaskDispatcher Dispatcher(Q);
- std::atomic<bool> TaskTaken = false;
-
- std::thread Consumer([&]() {
- auto Task = Q.takeFirstIn();
- TaskTaken = true;
- EXPECT_NE(Task, nullptr);
- Task->run();
- });
-
- // Give the consumer a moment to block.
- std::this_thread::sleep_for(std::chrono::milliseconds(50));
- EXPECT_FALSE(TaskTaken);
-
- // Dispatching a task should unblock the consumer.
- std::atomic<bool> TaskRan = false;
- Dispatcher.dispatch(makeGenericTask([&]() { TaskRan = true; }));
-
- Consumer.join();
-
- EXPECT_TRUE(TaskTaken);
- EXPECT_TRUE(TaskRan);
-
- Dispatcher.shutdown();
-}
-
-TEST(QueueingTaskDispatcherTest, TakeReturnsNullptrOnShutdown) {
- // Verify that a blocked take returns nullptr when the queue is shut down.
- QueueingTaskDispatcher::TaskQueue Q;
- QueueingTaskDispatcher Dispatcher(Q);
- std::atomic<bool> TakeReturned = false;
-
- std::thread Consumer([&]() {
- auto Task = Q.takeFirstIn();
- EXPECT_EQ(Task, nullptr);
- TakeReturned.store(true);
- });
-
- // Give the consumer a moment to block.
- std::this_thread::sleep_for(std::chrono::milliseconds(50));
- EXPECT_FALSE(TakeReturned);
-
- // Shutting down should unblock the consumer with nullptr.
- Dispatcher.shutdown();
-
- Consumer.join();
- EXPECT_TRUE(TakeReturned);
-}
-
-TEST(QueueingTaskDispatcherTest, ThreadSafety) {
- // Test thread safety with concurrent dispatch and take.
- QueueingTaskDispatcher::TaskQueue Q;
- QueueingTaskDispatcher Dispatcher(Q);
- constexpr int NumProducers = 4;
- constexpr int TasksPerProducer = 25;
- constexpr int TotalTasks = NumProducers * TasksPerProducer;
- std::atomic<int> TasksCompleted = 0;
-
- // Producer threads dispatch tasks.
- std::vector<std::thread> Producers;
- for (int I = 0; I < NumProducers; ++I) {
- Producers.emplace_back([&]() {
- for (int J = 0; J < TasksPerProducer; ++J)
- Dispatcher.dispatch(makeGenericTask([&]() { ++TasksCompleted; }));
- });
- }
-
- // Consumer thread takes and runs tasks until shutdown.
- std::thread Consumer([&]() {
- while (auto Task = Q.takeFirstIn())
- Task->run();
- });
-
- // Wait for all producers to finish, then shut down.
- for (auto &T : Producers)
- T.join();
- Dispatcher.shutdown();
-
- Consumer.join();
- EXPECT_EQ(TasksCompleted, TotalTasks);
-}
-
-} // end anonymous namespace
diff --git a/orc-rt/unittests/SessionTest.cpp b/orc-rt/unittests/SessionTest.cpp
index 9214629498a18..ff23967756df5 100644
--- a/orc-rt/unittests/SessionTest.cpp
+++ b/orc-rt/unittests/SessionTest.cpp
@@ -11,8 +11,8 @@
//===----------------------------------------------------------------------===//
#include "orc-rt/Session.h"
+#include "orc-rt/QueueingRunner.h"
#include "orc-rt/SPSWrapperFunction.h"
-#include "orc-rt/ThreadPoolTaskDispatcher.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
@@ -28,6 +28,8 @@ using namespace orc_rt;
using ::testing::Eq;
using ::testing::Optional;
+using TaskQueue = std::deque<move_only_function<void()>>;
+
class MockService : public Service {
public:
enum class Op { Detach, Shutdown };
@@ -79,47 +81,19 @@ class ConfigurableService : public Service {
void doMoreConfig(int) noexcept {}
};
-class EnqueueingDispatcher : public TaskDispatcher {
-public:
- using OnShutdownRunFn = move_only_function<void()>;
- EnqueueingDispatcher(std::deque<std::unique_ptr<Task>> &Tasks,
- OnShutdownRunFn OnShutdownRun = {})
- : Tasks(Tasks), OnShutdownRun(std::move(OnShutdownRun)) {}
- void dispatch(std::unique_ptr<Task> T) override {
- Tasks.push_back(std::move(T));
- }
- void shutdown() override {
- if (OnShutdownRun)
- OnShutdownRun();
- }
-
- /// Run up to NumTasks (arbitrarily many if NumTasks == std::nullopt) tasks
- /// from the front of the queue, returning the number actually run.
- static size_t
- runTasksFromFront(std::deque<std::unique_ptr<Task>> &Tasks,
- std::optional<size_t> NumTasks = std::nullopt) {
- size_t NumRun = 0;
-
- while (!Tasks.empty() && (!NumTasks || NumRun != *NumTasks)) {
- auto T = std::move(Tasks.front());
- Tasks.pop_front();
- T->run();
- ++NumRun;
- }
-
- return NumRun;
- }
-
-private:
- std::deque<std::unique_ptr<Task>> &Tasks;
- OnShutdownRunFn OnShutdownRun;
-};
-
class MockControllerAccess : public Session::ControllerAccess {
public:
using OnConnectFn = move_only_function<Error(BootstrapInfo &BI)>;
- MockControllerAccess(Session &SS) : Session::ControllerAccess(SS), SS(SS) {}
+ /// Hook used to defer controller-side work (the simulated controller
+ /// handler invocation, and the OnComplete callback for completed calls).
+ /// Tests typically wire this to push onto the same WorkQueue that the
+ /// Session's QueueingRunner uses, so that a single drain advances both
+ /// sides.
+ using PostFn = move_only_function<void(move_only_function<void()>)>;
+
+ MockControllerAccess(Session &SS, PostFn Post = {})
+ : Session::ControllerAccess(SS), Post(std::move(Post)) {}
void setOnConnect(OnConnectFn OnConnect) {
this->OnConnect = std::move(OnConnect);
@@ -143,8 +117,8 @@ class MockControllerAccess : public Session::ControllerAccess {
void callController(OnCallHandlerCompleteFn OnComplete, HandlerTag T,
WrapperFunctionBuffer ArgBytes) override {
- // Simulate a call to the controller by dispatching a task to run the
- // requested function.
+ // Simulate a call to the controller by running the requested function via
+ // the test-supplied Post hook (or inline, if no hook was provided).
size_t CId;
{
std::scoped_lock<std::mutex> Lock(M);
@@ -155,12 +129,11 @@ class MockControllerAccess : public Session::ControllerAccess {
++Outstanding;
}
- SS.dispatch(makeGenericTask([this, CId, OnComplete = std::move(OnComplete),
- T, ArgBytes = std::move(ArgBytes)]() mutable {
+ runOrPost([this, CId, T, ArgBytes = std::move(ArgBytes)]() mutable {
auto Fn = reinterpret_cast<orc_rt_WrapperFunction>(T);
Fn(reinterpret_cast<orc_rt_SessionRef>(this), CId, wfReturn,
ArgBytes.release());
- }));
+ });
bool Notify = false;
{
@@ -189,11 +162,10 @@ class MockControllerAccess : public Session::ControllerAccess {
++Outstanding;
}
- SS.dispatch(
- makeGenericTask([OnComplete = std::move(OnComplete),
- ResultBytes = std::move(ResultBytes)]() mutable {
- OnComplete(std::move(ResultBytes));
- }));
+ runOrPost([OnComplete = std::move(OnComplete),
+ ResultBytes = std::move(ResultBytes)]() mutable {
+ OnComplete(std::move(ResultBytes));
+ });
bool Notify = false;
{
@@ -255,6 +227,13 @@ class MockControllerAccess : public Session::ControllerAccess {
}
private:
+ void runOrPost(move_only_function<void()> Work) {
+ if (Post)
+ Post(std::move(Work));
+ else
+ Work();
+ }
+
static void wfReturn(orc_rt_SessionRef S, uint64_t CallId,
orc_rt_WrapperFunctionBuffer ResultBytes) {
// Abuse "session" to refer to the ControllerAccess object.
@@ -263,7 +242,7 @@ class MockControllerAccess : public Session::ControllerAccess {
CallId, WrapperFunctionBuffer(ResultBytes));
}
- Session &SS;
+ PostFn Post;
std::mutex M;
bool Shutdown = false;
@@ -289,6 +268,15 @@ class CallViaMockControllerAccess {
orc_rt_WrapperFunction Fn;
};
+/// Build a PostFn for MockControllerAccess that pushes its work onto the
+/// supplied queue. With this, a single
+/// QueueingRunner<TaskQueue>::runFIFOUntilEmpty(Q) call advances both
+/// Session-side and controller-side work.
+inline MockControllerAccess::PostFn postOnto(TaskQueue &Q) {
+ return
+ [&Q](move_only_function<void()> Work) { Q.push_back(std::move(Work)); };
+}
+
void waitForShutdown(Session &S) {
std::promise<void> P;
auto F = P.get_future();
@@ -297,15 +285,14 @@ void waitForShutdown(Session &S) {
}
TEST(SessionTest, TrivialConstructionAndDestruction) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
}
TEST(SessionTest, ReportError) {
Error E = Error::success();
cantFail(std::move(E)); // Force error into checked state.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
+ Session S(mockExecutorProcessInfo(), noDispatch,
[&](Error Err) { E = std::move(Err); });
S.reportError(make_error<StringError>("foo"));
@@ -315,29 +302,13 @@ TEST(SessionTest, ReportError) {
ADD_FAILURE() << "Missing error value";
}
-TEST(SessionTest, DispatchTask) {
- int X = 0;
- std::deque<std::unique_ptr<Task>> Tasks;
- Session S(mockExecutorProcessInfo(),
- std::make_unique<EnqueueingDispatcher>(Tasks), noErrors);
-
- EXPECT_EQ(Tasks.size(), 0U);
- S.dispatch(makeGenericTask([&]() { ++X; }));
- EXPECT_EQ(Tasks.size(), 1U);
- auto T = std::move(Tasks.front());
- Tasks.pop_front();
- T->run();
- EXPECT_EQ(X, 1);
-}
-
TEST(SessionTest, SingleService) {
size_t OpIdx = 0;
std::optional<size_t> DetachOpIdx;
std::optional<size_t> ShutdownOpIdx;
{
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
S.addService(
std::make_unique<MockService>(DetachOpIdx, ShutdownOpIdx, OpIdx));
}
@@ -353,8 +324,7 @@ TEST(SessionTest, MultipleServices) {
std::optional<size_t> ShutdownOpIdx[3];
{
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
for (size_t I = 0; I != 3; ++I)
S.addService(std::make_unique<MockService>(DetachOpIdx[I],
ShutdownOpIdx[I], OpIdx));
@@ -373,8 +343,7 @@ TEST(SessionTest, ScheduleShutdownFromOnDetachHandler) {
// 1. The shutdown is scheduled.
// 2. All onDetach handlers run before any onShutdown handlers.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
int OnDetachHandlersRun = 0;
bool OnShutdownHandlerRun = false;
@@ -394,9 +363,8 @@ TEST(SessionTest, ScheduleShutdownFromOnDetachHandler) {
TEST(SessionTest, RedundantAsyncShutdown) {
// Check that redundant calls to shutdown have their callbacks run.
- std::deque<std::unique_ptr<Task>> Tasks;
- Session S(mockExecutorProcessInfo(),
- std::make_unique<EnqueueingDispatcher>(Tasks), noErrors);
+ TaskQueue Tasks;
+ Session S(mockExecutorProcessInfo(), QueueingRunner(Tasks), noErrors);
// Initiate shutdown here, and wait for the on-shutdown callbacks to start
// running.
@@ -411,32 +379,22 @@ TEST(SessionTest, RedundantAsyncShutdown) {
TEST(SessionTest, ExpectedShutdownSequenceWithNoActiveManagedCodeCalls) {
// Check that Session shutdown results in...
// 1. Services being shut down.
- // 2. The TaskDispatcher being shut down.
- // 3. A call to OnShutdownComplete.
+ // 2. A call to OnShutdownComplete.
size_t OpIdx = 0;
std::optional<size_t> DetachOpIdx;
std::optional<size_t> ShutdownOpIdx;
- bool DispatcherShutDown = false;
bool SessionShutdownComplete = false;
{
- std::deque<std::unique_ptr<Task>> Tasks;
- Session S(mockExecutorProcessInfo(),
- std::make_unique<EnqueueingDispatcher>(
- Tasks,
- [&]() {
- EXPECT_TRUE(ShutdownOpIdx);
- EXPECT_EQ(*ShutdownOpIdx, 1);
- EXPECT_TRUE(SessionShutdownComplete);
- DispatcherShutDown = true;
- }),
- noErrors);
+ TaskQueue Tasks;
+ Session S(mockExecutorProcessInfo(), QueueingRunner(Tasks), noErrors);
S.addService(
std::make_unique<MockService>(DetachOpIdx, ShutdownOpIdx, OpIdx));
S.shutdown([&]() {
- EXPECT_FALSE(DispatcherShutDown);
+ EXPECT_TRUE(ShutdownOpIdx);
+ EXPECT_EQ(*ShutdownOpIdx, 1);
SessionShutdownComplete = true;
});
}
@@ -445,9 +403,8 @@ TEST(SessionTest, ExpectedShutdownSequenceWithNoActiveManagedCodeCalls) {
}
TEST(SessionTest, ActiveManagedCallsDelayShutdown) {
- std::deque<std::unique_ptr<Task>> Tasks;
- Session S(mockExecutorProcessInfo(),
- std::make_unique<EnqueueingDispatcher>(Tasks), noErrors);
+ TaskQueue Tasks;
+ Session S(mockExecutorProcessInfo(), QueueingRunner(Tasks), noErrors);
size_t OpIdx = 0;
std::optional<size_t> DetachOpIdx;
@@ -486,8 +443,7 @@ static void managedSyncVoidFunction(int *P) { *P = 42; }
TEST(SessionTest, SyncCallManagedCodeVoidFn) {
// Test synchronous calls to a void function while holding a
// ManagedCodeTaskGroup token.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
{
// Pre-shutdown we expect token acquisition to succeed and the function to
@@ -516,8 +472,7 @@ static int managedSyncNonVoidFunction(int N) { return N + 1; }
TEST(SessionTest, SyncCallManagedCodeNonVoidFn) {
// Test synchronous calls to a non-void function while holding a
// ManagedCodeTaskGroup token.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
{
// Pre-shutdown we expect token acquisition to succeed, the function to be
@@ -548,8 +503,7 @@ static void managedAsyncVoidFunction(move_only_function<void()> Return,
TEST(SessionTest, AsyncCallManagedCodeVoidFn) {
// Test asynchronous calls to a void function while holding a
// ManagedCodeTaskGroup token.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
{
// Pre-shutdown we expect token acquisition to succeed, and the function
@@ -584,8 +538,7 @@ static void managedAsyncNonVoidFunction(move_only_function<void(int)> Return,
TEST(SessionTest, AsyncCallManagedCodeNonVoidFn) {
// Test asynchronous calls to a non-void function while holding a
// ManagedCodeTaskGroup token.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
{
// Pre-shutdown we expect token acquisition to succeed, and the function
@@ -617,8 +570,7 @@ TEST(SessionTest, AsyncCallManagedCodeHoldsTokenAcrossAsyncGap) {
// Verify that the ManagedCodeTaskGroup token is held until the async
// continuation runs, not just until callManagedCodeAsync returns. This
// ensures shutdown blocks for the duration of the actual async work.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
size_t OpIdx = 0;
std::optional<size_t> DetachOpIdx;
@@ -662,22 +614,19 @@ TEST(SessionTest, AsyncCallManagedCodeHoldsTokenAcrossAsyncGap) {
}
TEST(SessionTest, AddServiceAndUseRef) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
auto &CS = S.addService(std::make_unique<ConfigurableService>(42));
CS.doMoreConfig(1);
}
TEST(SessionTest, CreateServiceAndUseRef) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
auto &CS = S.createService<ConfigurableService>(42);
CS.doMoreConfig(1);
}
TEST(SessionTest, TryCreateServiceSuccess) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
auto CS = S.tryCreateService<ConfigurableService>(false);
if (auto Err = CS.takeError()) {
ADD_FAILURE() << "expected service creation to succeed";
@@ -686,8 +635,7 @@ TEST(SessionTest, TryCreateServiceSuccess) {
}
TEST(SessionTest, TryCreateServiceFailure) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
auto CS = S.tryCreateService<ConfigurableService>(true);
if (auto Err = CS.takeError())
consumeError(std::move(Err));
@@ -698,12 +646,12 @@ TEST(SessionTest, TryCreateServiceFailure) {
TEST(ControllerAccessTest, Basics) {
// Test that we can set the ControllerAccess implementation and still shut
// down as expected.
- std::deque<std::unique_ptr<Task>> Tasks;
- Session S(mockExecutorProcessInfo(),
- std::make_unique<EnqueueingDispatcher>(Tasks), noErrors);
- S.attach<MockControllerAccess>(BootstrapInfo(S), S);
+ TaskQueue Tasks;
+ Session S(mockExecutorProcessInfo(), QueueingRunner(Tasks), noErrors);
+ S.attach(std::make_shared<MockControllerAccess>(S, postOnto(Tasks)),
+ BootstrapInfo(S));
- EnqueueingDispatcher::runTasksFromFront(Tasks);
+ QueueingRunner<TaskQueue>::runFIFOUntilEmpty(Tasks);
}
static void add_sps_wrapper(orc_rt_SessionRef S, uint64_t CallId,
@@ -718,26 +666,25 @@ static void add_sps_wrapper(orc_rt_SessionRef S, uint64_t CallId,
TEST(ControllerAccessTest, ValidCallToController) {
// Simulate a call to a controller handler.
- std::deque<std::unique_ptr<Task>> Tasks;
- Session S(mockExecutorProcessInfo(),
- std::make_unique<EnqueueingDispatcher>(Tasks), noErrors);
- S.attach<MockControllerAccess>(BootstrapInfo(S), S);
+ TaskQueue Tasks;
+ Session S(mockExecutorProcessInfo(), QueueingRunner(Tasks), noErrors);
+ S.attach(std::make_shared<MockControllerAccess>(S, postOnto(Tasks)),
+ BootstrapInfo(S));
int32_t Result = 0;
SPSWrapperFunction<int32_t(int32_t, int32_t)>::call(
S.callViaSession(reinterpret_cast<Session::HandlerTag>(add_sps_wrapper)),
[&](Expected<int32_t> R) { Result = cantFail(std::move(R)); }, 41, 1);
- EnqueueingDispatcher::runTasksFromFront(Tasks);
+ QueueingRunner<TaskQueue>::runFIFOUntilEmpty(Tasks);
EXPECT_EQ(Result, 42);
}
TEST(ControllerAccessTest, CallToControllerBeforeAttach) {
// Expect calls to the controller prior to attaching to fail.
- std::deque<std::unique_ptr<Task>> Tasks;
- Session S(mockExecutorProcessInfo(),
- std::make_unique<EnqueueingDispatcher>(Tasks), noErrors);
+ TaskQueue Tasks;
+ Session S(mockExecutorProcessInfo(), QueueingRunner(Tasks), noErrors);
Error Err = Error::success();
SPSWrapperFunction<int32_t(int32_t, int32_t)>::call(
@@ -753,10 +700,10 @@ TEST(ControllerAccessTest, CallToControllerBeforeAttach) {
TEST(ControllerAccessTest, CallToControllerAfterDetach) {
// Expect calls to the controller prior to attaching to fail.
- std::deque<std::unique_ptr<Task>> Tasks;
- Session S(mockExecutorProcessInfo(),
- std::make_unique<EnqueueingDispatcher>(Tasks), noErrors);
- S.attach<MockControllerAccess>(BootstrapInfo(S), S);
+ TaskQueue Tasks;
+ Session S(mockExecutorProcessInfo(), QueueingRunner(Tasks), noErrors);
+ S.attach(std::make_shared<MockControllerAccess>(S, postOnto(Tasks)),
+ BootstrapInfo(S));
S.detach();
@@ -774,10 +721,9 @@ TEST(ControllerAccessTest, CallToControllerAfterDetach) {
TEST(ControllerAccessTest, CallFromController) {
// Simulate a call from the controller.
- std::deque<std::unique_ptr<Task>> Tasks;
- Session S(mockExecutorProcessInfo(),
- std::make_unique<EnqueueingDispatcher>(Tasks), noErrors);
- auto CA = std::make_shared<MockControllerAccess>(S);
+ TaskQueue Tasks;
+ Session S(mockExecutorProcessInfo(), QueueingRunner(Tasks), noErrors);
+ auto CA = std::make_shared<MockControllerAccess>(S, postOnto(Tasks));
S.attach(CA, BootstrapInfo(S));
int32_t Result = 0;
@@ -785,7 +731,7 @@ TEST(ControllerAccessTest, CallFromController) {
CallViaMockControllerAccess(*CA, add_sps_wrapper),
[&](Expected<int32_t> R) { Result = cantFail(std::move(R)); }, 41, 1);
- EnqueueingDispatcher::runTasksFromFront(Tasks);
+ QueueingRunner<TaskQueue>::runFIFOUntilEmpty(Tasks);
EXPECT_EQ(Result, 42);
}
@@ -794,11 +740,10 @@ TEST(ControllerAccessTest, FailConnect) {
// Simulate failure to connect.
bool GotError = false;
std::string ErrMsg = "failed to connect";
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- [&](Error Err) {
- GotError = true;
- EXPECT_EQ(toString(std::move(Err)), ErrMsg);
- });
+ Session S(mockExecutorProcessInfo(), noDispatch, [&](Error Err) {
+ GotError = true;
+ EXPECT_EQ(toString(std::move(Err)), ErrMsg);
+ });
BootstrapInfo BI(S);
auto CA = std::make_shared<MockControllerAccess>(S);
CA->setOnConnect(
@@ -808,8 +753,7 @@ TEST(ControllerAccessTest, FailConnect) {
}
TEST(ControllerAccessTest, BootstrapInfoPassedToConnect) {
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
// Test values.
constexpr const char *SymName = "test_sym";
diff --git a/orc-rt/unittests/SimpleNativeMemoryMapSPSCITest.cpp b/orc-rt/unittests/SimpleNativeMemoryMapSPSCITest.cpp
index 435ab91df66cf..397e699bb6cc9 100644
--- a/orc-rt/unittests/SimpleNativeMemoryMapSPSCITest.cpp
+++ b/orc-rt/unittests/SimpleNativeMemoryMapSPSCITest.cpp
@@ -113,8 +113,8 @@ read_value_sps_allocaction(const char *ArgData, size_t ArgSize) {
class SimpleNativeMemoryMapSPSCITest : public ::testing::Test {
protected:
void SetUp() override {
- S = std::make_unique<Session>(mockExecutorProcessInfo(),
- std::make_unique<NoDispatcher>(), noErrors);
+ S = std::make_unique<Session>(mockExecutorProcessInfo(), noDispatch,
+ noErrors);
SNMM = cantFail(SimpleNativeMemoryMap::Create(*S, CI));
}
diff --git a/orc-rt/unittests/SimpleNativeMemoryMapTest.cpp b/orc-rt/unittests/SimpleNativeMemoryMapTest.cpp
index 151237a550f6f..ce60251697a89 100644
--- a/orc-rt/unittests/SimpleNativeMemoryMapTest.cpp
+++ b/orc-rt/unittests/SimpleNativeMemoryMapTest.cpp
@@ -51,8 +51,7 @@ read_value_sps_allocaction(const char *ArgData, size_t ArgSize) {
TEST(SimpleNativeMemoryMapTest, CreateAndDestroy) {
// Test that we can create and destroy a SimpleNativeMemoryMap instance as
// expected.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ThrowAway;
auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
}
@@ -60,8 +59,7 @@ TEST(SimpleNativeMemoryMapTest, CreateAndDestroy) {
TEST(SimpleNativeMemoryMapTest, ReserveAndRelease) {
// Test that we can reserve and release a slab of address space as expected,
// without finalizing any memory within it.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ThrowAway;
auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
@@ -83,8 +81,7 @@ TEST(SimpleNativeMemoryMapTest, FullPipelineForOneRWSegment) {
// expected.
// 4. release the address range.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ThrowAway;
auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
@@ -160,8 +157,7 @@ TEST(SimpleNativeMemoryMapTest, FullPipelineForOneRWSegment) {
TEST(SimpleNativeMemoryMapTest, ReserveRejectsNonPageSizeMultiple) {
// Verify that reserve rejects sizes that aren't page-size multiples.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ThrowAway;
auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
@@ -174,8 +170,7 @@ TEST(SimpleNativeMemoryMapTest, ReserveRejectsNonPageSizeMultiple) {
TEST(SimpleNativeMemoryMapTest, ReserveAcceptsPageSizeMultiple) {
// Verify that reserve accepts a size that's an exact page-size multiple.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ThrowAway;
auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
@@ -192,7 +187,7 @@ TEST(SimpleNativeMemoryMapTest, ReleaseMultipleReportsErrors) {
// Test that releaseMultiple reports errors via Session::reportError
// when some addresses aren't recognized.
std::vector<std::string> Errors;
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
+ Session S(mockExecutorProcessInfo(), noDispatch,
[&](Error Err) { Errors.push_back(toString(std::move(Err))); });
SimpleSymbolTable ThrowAway;
auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
@@ -214,7 +209,7 @@ TEST(SimpleNativeMemoryMapTest, DeinitializeMultipleReportsErrors) {
// Test that deinitializeMultiple reports errors via Session::reportError
// when some addresses aren't recognized.
std::vector<std::string> Errors;
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
+ Session S(mockExecutorProcessInfo(), noDispatch,
[&](Error Err) { Errors.push_back(toString(std::move(Err))); });
SimpleSymbolTable ThrowAway;
auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
@@ -243,8 +238,7 @@ TEST(SimpleNativeMemoryMapTest, ReserveInitializeShutdown) {
// Test that memory is deinitialized in the case where we reserve and
// initialize some memory, then just shut down the memory manager.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ThrowAway;
auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
@@ -285,8 +279,7 @@ TEST(SimpleNativeMemoryMapTest, ReserveInitializeDetachShutdown) {
// Test that memory is deinitialized in the case where we reserve and
// initialize some memory, then just shut down the memory manager.
- Session S(mockExecutorProcessInfo(), std::make_unique<NoDispatcher>(),
- noErrors);
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
SimpleSymbolTable ThrowAway;
auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
diff --git a/orc-rt/unittests/ThreadPoolRunnerTest.cpp b/orc-rt/unittests/ThreadPoolRunnerTest.cpp
new file mode 100644
index 0000000000000..e023af76b1f30
--- /dev/null
+++ b/orc-rt/unittests/ThreadPoolRunnerTest.cpp
@@ -0,0 +1,153 @@
+//===- ThreadPoolRunnerTest.cpp ---------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt/ThreadPoolRunner.h"
+#include "orc-rt/SPSWrapperFunction.h"
+#include "gtest/gtest.h"
+
+#include <atomic>
+#include <cstdint>
+#include <future>
+#include <thread>
+
+using namespace orc_rt;
+
+namespace {
+
+inline orc_rt_SessionRef dummySession() noexcept {
+ return reinterpret_cast<orc_rt_SessionRef>(uintptr_t{0xABCD});
+}
+
+inline orc_rt_WrapperFunctionReturn dummyReturn() noexcept {
+ return [](orc_rt_SessionRef, uint64_t, orc_rt_WrapperFunctionBuffer) {};
+}
+
+template <typename T> WrapperFunctionBuffer serializePtr(T *Ptr) {
+ auto Buf = WrapperFunctionSPSSerializer<void(SPSExecutorAddr)>::arguments()
+ .serialize(Ptr);
+ assert(Buf && "failed to serialize pointer arg");
+ return std::move(*Buf);
+}
+
+TEST(ThreadPoolRunnerTest, NoCalls) {
+ // Check that immediate destruction works as expected.
+ ThreadPoolRunner R(1);
+}
+
+static void signalPromise(orc_rt_SessionRef S, uint64_t CallId,
+ orc_rt_WrapperFunctionReturn Return,
+ orc_rt_WrapperFunctionBuffer ArgBytes) {
+ SPSWrapperFunction<void(SPSExecutorAddr)>::handle(
+ S, CallId, Return, ArgBytes,
+ [](move_only_function<void()> Return, ExecutorAddr P) {
+ P.toPtr<std::promise<void> *>()->set_value();
+ Return();
+ });
+}
+
+TEST(ThreadPoolRunnerTest, BasicCallExecution) {
+ // Smoke test: dispatch one call on a single-threaded pool, wait for it to
+ // run, then let the runner destruct.
+ std::promise<void> Done;
+ std::future<void> DoneF = Done.get_future();
+
+ {
+ ThreadPoolRunner R(1);
+ R(dummySession(), 0, dummyReturn(), signalPromise, serializePtr(&Done));
+ DoneF.get();
+ }
+}
+
+static void incrementCounter(orc_rt_SessionRef S, uint64_t CallId,
+ orc_rt_WrapperFunctionReturn Return,
+ orc_rt_WrapperFunctionBuffer ArgBytes) {
+ SPSWrapperFunction<void(SPSExecutorAddr)>::handle(
+ S, CallId, Return, ArgBytes,
+ [](move_only_function<void()> Return, ExecutorAddr P) {
+ ++*P.toPtr<std::atomic<size_t> *>();
+ Return();
+ });
+}
+
+TEST(ThreadPoolRunnerTest, SingleThreadMultipleCalls) {
+ // Dispatch multiple calls on a single-threaded pool, wait for all to run,
+ // then let the runner destruct.
+ size_t NumCallsToRun = 10;
+ std::atomic<size_t> CallsRun = 0;
+
+ {
+ ThreadPoolRunner R(1);
+ for (size_t I = 0; I != NumCallsToRun; ++I)
+ R(dummySession(), I, dummyReturn(), incrementCounter,
+ serializePtr(&CallsRun));
+
+ // while (CallsRun.load() < NumCallsToRun)
+ // std::this_thread::yield();
+ }
+
+ EXPECT_EQ(CallsRun, NumCallsToRun);
+}
+
+struct ConcurrencyState {
+ std::future<int> FInit;
+ std::promise<int> P1;
+ std::promise<int> P2;
+ std::future<int> F1 = P1.get_future();
+ std::future<int> F2 = P2.get_future();
+ std::promise<int> PResult;
+};
+
+static void concurrencyTaskA(orc_rt_SessionRef S, uint64_t CallId,
+ orc_rt_WrapperFunctionReturn Return,
+ orc_rt_WrapperFunctionBuffer ArgBytes) {
+ SPSWrapperFunction<void(SPSExecutorAddr)>::handle(
+ S, CallId, Return, ArgBytes,
+ [](move_only_function<void()> Return, ExecutorAddr P) {
+ auto *State = P.toPtr<ConcurrencyState *>();
+ State->P1.set_value(State->FInit.get());
+ State->PResult.set_value(State->F2.get());
+ Return();
+ });
+}
+
+static void concurrencyTaskB(orc_rt_SessionRef S, uint64_t CallId,
+ orc_rt_WrapperFunctionReturn Return,
+ orc_rt_WrapperFunctionBuffer ArgBytes) {
+ SPSWrapperFunction<void(SPSExecutorAddr)>::handle(
+ S, CallId, Return, ArgBytes,
+ [](move_only_function<void()> Return, ExecutorAddr P) {
+ auto *State = P.toPtr<ConcurrencyState *>();
+ State->P2.set_value(State->F1.get());
+ Return();
+ });
+}
+
+TEST(ThreadPoolRunnerTest, ConcurrentCalls) {
+ // Check that calls run concurrently when multiple workers are available.
+ // Two calls communicate values back and forth via futures; neither can
+ // complete without the other having started. FResult.get() also serves
+ // as the "all calls have run" wait point before destruction.
+ std::promise<int> PInit;
+ ConcurrencyState State;
+ State.FInit = PInit.get_future();
+ std::future<int> FResult = State.PResult.get_future();
+
+ int ExpectedValue = 42;
+
+ {
+ ThreadPoolRunner R(2);
+ R(dummySession(), 0, dummyReturn(), concurrencyTaskA, serializePtr(&State));
+ R(dummySession(), 1, dummyReturn(), concurrencyTaskB, serializePtr(&State));
+
+ PInit.set_value(ExpectedValue);
+
+ EXPECT_EQ(FResult.get(), ExpectedValue);
+ }
+}
+
+} // end anonymous namespace
diff --git a/orc-rt/unittests/ThreadPoolTaskDispatcherTest.cpp b/orc-rt/unittests/ThreadPoolTaskDispatcherTest.cpp
deleted file mode 100644
index 02cca94a494ff..0000000000000
--- a/orc-rt/unittests/ThreadPoolTaskDispatcherTest.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-//===-- ThreadPoolTaskDispatcherTest.cpp ----------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/ThreadPoolTaskDispatcher.h"
-#include "gtest/gtest.h"
-
-#include <atomic>
-#include <future>
-#include <thread>
-#include <vector>
-
-using namespace orc_rt;
-
-namespace {
-
-TEST(ThreadPoolTaskDispatcherTest, NoTasks) {
- // Check that immediate shutdown works as expected.
- ThreadPoolTaskDispatcher Dispatcher(1);
- Dispatcher.shutdown();
-}
-
-TEST(ThreadPoolTaskDispatcherTest, BasicTaskExecution) {
- // Smoke test: Check that we can run a single task on a single-threaded pool.
- ThreadPoolTaskDispatcher Dispatcher(1);
- std::atomic<bool> TaskRan = false;
-
- Dispatcher.dispatch(makeGenericTask([&]() { TaskRan = true; }));
-
- Dispatcher.shutdown();
-
- EXPECT_TRUE(TaskRan);
-}
-
-TEST(ThreadPoolTaskDispatcherTest, SingleThreadMultipleTasks) {
- // Check that multiple tasks in a single threaded pool run as expected.
- ThreadPoolTaskDispatcher Dispatcher(1);
- size_t NumTasksToRun = 10;
- std::atomic<size_t> TasksRun = 0;
-
- for (size_t I = 0; I != NumTasksToRun; ++I)
- Dispatcher.dispatch(makeGenericTask([&]() { ++TasksRun; }));
-
- Dispatcher.shutdown();
-
- EXPECT_EQ(TasksRun, NumTasksToRun);
-}
-
-TEST(ThreadPoolTaskDispatcherTest, ConcurrentTasks) {
- // Check that tasks are run concurrently when multiple workers are available.
- // Adds two tasks that communicate a value back and forth using futures.
- // Neither task should be able to complete without the other having started.
- ThreadPoolTaskDispatcher Dispatcher(2);
-
- std::promise<int> PInit;
- std::future<int> FInit = PInit.get_future();
- std::promise<int> P1;
- std::future<int> F1 = P1.get_future();
- std::promise<int> P2;
- std::future<int> F2 = P2.get_future();
- std::promise<int> PResult;
- std::future<int> FResult = PResult.get_future();
-
- // Task A gets the initial value, sends it via P1, waits for response on F2.
- Dispatcher.dispatch(makeGenericTask([&]() {
- P1.set_value(FInit.get());
- PResult.set_value(F2.get());
- }));
-
- // Task B gets value from F1, sends it back on P2.
- Dispatcher.dispatch(makeGenericTask([&]() { P2.set_value(F1.get()); }));
-
- int ExpectedValue = 42;
- PInit.set_value(ExpectedValue);
-
- Dispatcher.shutdown();
-
- EXPECT_EQ(FResult.get(), ExpectedValue);
-}
-
-TEST(ThreadPoolTaskDispatcherTest, TasksRejectedAfterShutdown) {
- class TaskToReject : public Task {
- public:
- TaskToReject(bool &BodyRun, bool &DestructorRun)
- : BodyRun(BodyRun), DestructorRun(DestructorRun) {}
- ~TaskToReject() { DestructorRun = true; }
- void run() override { BodyRun = true; }
-
- private:
- bool &BodyRun;
- bool &DestructorRun;
- };
-
- ThreadPoolTaskDispatcher Dispatcher(1);
- Dispatcher.shutdown();
-
- bool BodyRun = false;
- bool DestructorRun = false;
-
- Dispatcher.dispatch(std::make_unique<TaskToReject>(BodyRun, DestructorRun));
-
- EXPECT_FALSE(BodyRun);
- EXPECT_TRUE(DestructorRun);
-}
-
-} // end anonymous namespace
More information about the llvm-commits
mailing list