projects /
Venus executor
Yet another executor library, because I needed something simple and could not find it.
- C++14
- Concurrency
- MIT
Summary
Venus is a header-only C++14 library for running work on other threads without writing locks around your data. It has three building blocks: a single thread executor that runs tasks strictly in order, a pool executor that spreads independent tasks over all cores, and a dispatcher that combines both, inspired by Grand Central Dispatch. It needs nothing but the standard library.
The README is honest about its ambition: if this sounds too trivial, that is good, because that is what I am aiming for.
Note: these are not the executors of C++26 std::execution (senders/receivers). See how venus differs below.
Why it exists
Most C++ programs that use threads start the same way. There is some data, several actors want to change it, and a std::mutex appears next to it. Then a second mutex for the second data structure. Then a condition variable. A few months later a task that holds one lock calls a function that wants another, and the program deadlocks once a week on a customer machine.
The problems that venus tries to solve are the common, repeating ones, and usually one or more apply to a program at the same time:
- A data set has to be modified by multiple actors, possibly on different threads.
- Work has to be parallelized.
- Results have to be synchronized or sequentialized periodically.
- Work has to be dispatched to the background, with a callback that delivers the result.
Executors are not part of the C++ standard library yet, so I built the smallest thing that does the job. The tools involved are the ones every C++ programmer already knows: queues, std::mutex, std::thread and std::condition_variable. I looked online for a library that did only this, and found either something far bigger, or something that only did half of it. So: yet another executor.
A note on the name: venus executors are not exactly the “executors” of the C++ standard proposals, nor the parallel STL. I kept the word because it fits well. An executor is an object that you hand a function, and that promises to run it somewhere else, at some point, under rules you know.
The three executors
Single thread executor: venus::executor
This executor owns one thread and one queue. Tasks run one after another in the exact order they were added. That gives a hard first-come-first-served guarantee, and it makes one powerful thing true: everything that runs on the executor is thread-safe with respect to everything else on it, without a lock around your data.
There still is a lock, but only one, and only in the queue. Compare that with the usual alternative of several mutexes in several places, each locked and unlocked several times per operation. Here the lock is touched when work is queued, nowhere else.
venus::executor executor;
executor.add([&] { model.update(); }); // fire and forget
auto answer = executor.call_async([&] { return model.size(); }); // std::future<size_t>
std::size_t size = executor.call([&] { return model.size(); }); // blocks until done
The executor also runs timers: call_at, call_after and call_every. They return a scheduled_call handle that you can cancel. There is a rule to know about, and the documentation states it: queued tasks always go before timers, so a continuous flood of tasks delays timers. This is on purpose, and it is something to keep in mind in a system that is very busy.
The single thread executor is the tool to synchronize and gather.
Pool executor: venus::pool_executor
The pool executor has one queue and several threads, by default one per core. Tasks are picked up on a best-effort basis as soon as a thread is free. There is no guarantee about when a task runs or in what order, and that is the point.
venus::pool_executor pool;
pool.add([] { /* independent work */ });
auto result = pool.call_async([] { return 42; }); // std::future<int>
pool.wait_idle();
The pool supports parallelism, which is not the same as concurrency. In parallelism, tasks are by definition independent and do not touch the same data. That is why the pool offers no thread-safety features at all: if your tasks need them, you are using the wrong executor, or the wrong design.
The pool executor is the tool to scatter work over the machine.
Dispatcher: venus::dispatcher
The dispatcher takes the parts of Grand Central Dispatch that give most of the benefit, and leaves the rest, without depending on GCD:
- One fixed pool of threads, shared by all producers.
- Three priorities,
high,normalandlow. A thread always takes the oldest task of the highest priority. dispatch()runs tasks in parallel, as the pool executor does.make_serial_queue()creates a serial queue: tasks of one serial queue run one at a time, in order, as on a single thread executor.
The last point is the interesting one. A serial queue is not a thread. It is a cheap object, so you can have one per producer, per data structure or per subsystem, and they all share the same cores. Ten thousand serial queues do not cost ten thousand threads.
A serial queue with work occupies at most one thread at a time. After a batch of 16 tasks it goes to the back of its priority, so one busy queue cannot starve the others. Higher priority work always goes first.
venus::dispatcher dispatcher;
auto model = dispatcher.make_serial_queue(venus::priority::high);
dispatcher.dispatch([&] {
auto result = heavy_computation(); // runs in parallel
model.dispatch([&, result] { apply_to_model(result); }); // runs serialized, no locks needed
}, venus::priority::low);
This is a complete pattern in six lines: the expensive part runs wherever there is a free core at low priority, and the result is applied to the model on its own serial queue, in order, with no mutex anywhere.
Using them together
The executors are meant to cooperate. Suppose you have parallel work that needs to read and write data that other tasks can also access. The tempting solution is a mutex. The problem is that a task on a pool that blocks on a lock is a core that sits idle while other work could be done, and in the worst case all pool threads are waiting for one lock.
The strategy that venus recommends instead has three steps:
- Schedule a task on the single thread executor (or a serial queue). There, copy the data you need, or if the job is small, just do the work.
- At the end of that task, schedule the parallel work on the pool executor (or the dispatcher).
- At the end of the parallel work, schedule a task back on the single thread executor to process the result.
The data is only ever touched on the serial side, so it needs no lock. The parallel side only works on its own copy, so it never waits. Each part does the thing it is good at.
The guidelines that follow from this are short:
- Tasks on the pool should not take locks or do blocking I/O, and they should not need to.
- It is fine for tasks on the pool to take a long time.
- Tasks on the single thread executor block every other task in its queue, so keep them as short as possible.
This is the same idea that shows up in actor systems, in Grand Central Dispatch, in GUI event loops and in the paper that the README lists as a reference: share nothing between threads, and pass messages instead. Venus gives you the message passing part in a form that fits in your head.
Exceptions and lifetime
Concurrency libraries are mostly judged by what they do in the corner cases, so these are written down:
- Exceptions thrown by tasks started with
call(),call_async()anddispatch_async()are delivered through the returned future. Exceptions from other tasks are caught and ignored: they do not stop the executor. - The destructors of
pool_executoranddispatcherwait until all tasks are finished, including tasks added by tasks. The destructor ofexecutorruns the tasks that were queued before it, and discards timers that have not run yet. - A task that waits for its own executor would deadlock. Venus does not let that happen quietly:
executor::synchronize()on the executor thread, andwait_idle()from a task on the same pool or dispatcher, throwstd::logic_error. - A dispatcher must outlive its serial queues. Tasks dispatched to a serial queue still run when the queue object is destroyed.
- Using an executor while it is being destroyed violates the C++ object lifetime rules, and calling
cancel()on ascheduled_callafter its executor is gone does nothing.
How it is built
The implementation is small enough to read in an afternoon. A few of the pieces are interesting on their own:
guarded_notify<T> holds a T that can only be reached while holding a lock, together with a condition variable. You pass a lambda to with_lock, and the data is handed to you inside it. Waiting is the same: you pass the condition as a lambda, and the wait loop and the spurious-wakeup handling are done for you. Every change notifies all waiters, deliberately: different waiters can wait for different conditions on the same variable, and with notify_one() a waiter for the wrong condition could swallow the notification and leave the right one asleep forever (a lost wake-up).
synchronized_queue<T> is a queue built on guarded_notify, with an optional maximum size. A producer can wait for room, a consumer can wait for an item, and both waits come with timeout and deadline versions.
venus::task is a move-only void() callable, like a std::function<void()> that does not require copying. That sounds like a detail until you want a task that owns a std::unique_ptr or a std::packaged_task. With std::function you wrap it in a shared_ptr to get it through; with venus::task you simply move it in.
scheduled_calls is the timer list: a vector kept sorted by deadline, so the next one is always at the back and removing it is cheap. Repeating calls are rescheduled when popped.
Clocks. Timers use std::chrono::steady_clock, so adjusting the system clock should not affect them. There is one known exception that the documentation points out: libstdc++ before GCC 10 converts to system_clock internally when waiting, so on those compilers a clock adjustment can make a timer fire early or late. GCC 10 and later, and MSVC, wait on the steady clock as intended.
Portability and testing
For a library this small, the testing effort is deliberately large, because threading bugs hide.
- Dependencies: none beyond the standard library, and C++14 is enough. Venus is header-only: copy
src/executor/includeinto your project, or use the single headervenus.hpp, which the build generates from the separate headers. - CI: builds and tests with GCC, Clang, AppleClang and MSVC, in C++14 and C++17, with address, undefined behaviour and thread sanitizers. The thread sanitizer is the important one for this kind of code.
- Old compilers: the examples are compiled and run on Compiler Explorer with every GCC from 4.9.0 to 16.2 and Clang from 3.5 to 15, using a small Python script that talks to its API. The test fails when a compiler reports a warning in a venus header, because such a warning would show up in the build of everyone who uses the library.
- Unit tests use googletest and cover the queue, the task type, each executor, the headers (each compiles on its own) and the single header.
GCC 4.9 is the oldest supported compiler. If you work on a code base that is stuck on an old toolchain, it is a library you can still use.
Try it online
You can run the three examples without installing anything. Each opens in Compiler Explorer with GCC 4.9.2 and GCC 16.2 side by side, showing the assembly and the program output for both, and includes the single header straight from GitHub, so they always use the latest version:
#include <https://raw.githubusercontent.com/janwilmans/venus/refs/heads/main/src/executor/include/venus.hpp>
venus::executor: many producers, one thread that executes all tasks in order, and timers.venus::pool_executor: a parallel sum on all cores.venus::dispatcher: parallel work at low priority, with the results applied on a serial queue without locks.
The links are in the README.
Using it in your project
With CMake and FetchContent:
include(FetchContent)
FetchContent_Declare(venus
GIT_REPOSITORY https://github.com/janwilmans/venus.git
GIT_TAG main # better: a specific commit
)
FetchContent_MakeAvailable(venus)
target_link_libraries(my_target PRIVATE venus::executor)
add_subdirectory(venus) and find_package(venus REQUIRED) after a cmake --install also work. When venus is used by another project, its tests are not built (so googletest is not downloaded) and it is not compiled with extra warnings or -Werror. The options only default to on for a top-level build:
| Option | Meaning |
|---|---|
VENUS_BUILD_TESTS |
build the tests and examples |
VENUS_WARNINGS |
extra warnings, and warnings as errors |
VENUS_INSTALL |
generate the install target |
VENUS_SINGLE_HEADER |
regenerate venus.hpp during the build |
VENUS_SANITIZE |
sanitizers to enable, for example address,undefined or thread |
The headers are included as #include "executor/dispatcher.hpp", or all at once with #include "venus.hpp".
How venus differs from std::execution and senders/receivers
The word “executor” means different things in C++, so here is how venus relates to the standard’s work.
std::execution (C++26) is the senders/receivers framework. The execution control library is the standardized form of the senders/receivers design (P2300), so these are one thing, not two. Its building blocks are:
- A scheduler is a handle to an execution resource, such as a thread pool or an event loop. It does not run anything itself.
- A sender is a description of asynchronous work. Creating one starts nothing. You compose senders with algorithms such as
then,let_value,when_allandcontinues_on, and you can move work between schedulers. - A receiver is what the work reports to. It has three completion channels: value, error and stopped (cancellation).
- Nothing runs until the sender is connected to a receiver, which gives an operation state, and that is started.
The result is a lazy, composable and statically typed pipeline: errors, cancellation and the choice of where each step runs are part of the type system, and the compiler can often remove the allocations. The cost is a larger vocabulary and heavier template machinery.
Venus is the other end of the spectrum. It is eager and imperative:
senders/receivers (std::execution) |
venus | |
|---|---|---|
| Unit of work | a lazy description that you compose before starting | a callable that is queued and starts running as soon as a thread is free |
| Composition | algorithms (then, let_value, when_all, …) |
you chain by queueing the next task from the end of the previous one |
| Results and errors | completion channels: value, error, stopped | a std::future, or nothing for fire-and-forget tasks |
| Cancellation | built in (stop tokens, the stopped channel) | only for timers (scheduled_call::cancel()) |
| Where code runs | chosen with schedulers, per step | chosen by which executor or serial queue you add the task to |
| Thread safety | up to you | the single thread executor and serial queues serialize access to your data |
| Language level | C++26 | C++14 |
Two further differences matter in practice:
- Strand versus sequence. The central idea in venus is serialization: one executor or serial queue owns a piece of data, and everything that touches it runs there, in order. Senders/receivers describe the flow of a computation, and leave protecting shared state to you. The two ideas can be combined, since a serial queue could be wrapped as a scheduler.
- Goal.
std::executionis a foundation for libraries: a vocabulary that thread pools, I/O frameworks and GPU runtimes can all speak. Venus is a ready-to-use tool for one common job, parallel work whose results are applied sequentially, in a header you can read in an afternoon.
If you need composition across libraries, structured cancellation or coroutines, use std::execution (or an implementation of P2300 such as stdexec). If you need a few background threads and some safe, ordered access to your data on a C++14 toolchain, venus is enough.
When not to use venus
An honest description includes the limits.
- It is not an asynchronous I/O framework. There is no event loop around sockets and no coroutine support. If you need that, look at Asio.
- It is not a work-stealing scheduler. The pool has one shared queue, which is simple and fair, and which will not scale to a very large number of very small tasks on a very large number of cores as well as a more elaborate design.
- It is not the standard
std::execution(senders and receivers) model; see the comparison above. Venus offers a smaller idea with a lower learning curve. - There is no cancellation of queued tasks apart from timers, and no task dependency graph.
If your needs are a few threads, a few data structures that need protecting and some background work with callbacks, which is most programs, then a small tool you can read completely is often the better choice.
License
MIT, copyright Jan Wilmans. Use it, copy the header into your project, let me know what you used it for and whether you liked using it.