The project isn't being actively developed. Follow here (Gerold103/serverbox) for further evolution.
TaskScheduler
TaskScheduler is a set of algorithms for asynchronous threaded code execution.
The scheduler runs so called tasks which have a simple API of their own plus user can attach to them anything in form of callbacks.
A very simple example:
TaskScheduler sched("name", thread_count, queue_size);
Task* t = new Task([](Task *self) {
printf("Executed in scheduler!\n");
delete self;
});
sched.Post(t);
Description
Use cases
Not limited by these, but most typical:
- Single shot mildly heavy tasks;
- Massive load of millions of quick tasks;
- Fair load of heavy multi-step tasks (aka coroutines);
To use the task as coroutines the scheduler offers features like task sleeping, wakeup deadlines, explicit wakeups, signal delivery to individual tasks.
Fairness
The task execution is fair. It means they are not pinned to threads. That in turn gives even CPU load on all workers. It will not happen that some tasks appear to be too heavy and occupy one thread's CPU 100% while other threads do nothing.
The execution is also fair in terms of order. Meaning that the tasks start execution in worker threads in the same order as were posted (unless have different deadlines). Although it obviously doesn't guarantee that they end in the same order (unless the worker thread is just one).
Performance
The performance depends on thread count and task durations. An example of how it can look:
- 2.30 GHz Intel Xeon, 8 physical cores;
- 2 worker threads;
- A task body takes up to tens of nanoseconds, quite short. Worst case scenario for contention.
That gives more than 5 millions of tasks per second. For more info see bench folder with detailed reports and if want to run them locally.
Correctness
The algorithms used in the scheduler are validated in TLA+ specifications to ensure absence of deadlocks, unintentional reordering, task loss, and other logical mistakes.
Getting Started
Dependencies
- At least C++11;
- A standard C++ library. On non-Windows also need
pthread library.
- Compiler support:
- Windows MSVC;
- Clang;
- GCC;
- OS should be any version of Linux, Windows, WSL, Mac. The actual testing was done on:
- Windows 10;
- WSLv1;
- Debian 4.19;
- MacOS Catalina 10.15.5;
- Supports only architecture x86-64. On ARM it might work, but wasn't compiled nor tested;
- CMake. Compatible with
cmake CLI and with VisualStudio CMake.
Build and test
Visual Studio
- Open VisualStudio;
- Select "Open a local folder";
- Select
TaskScheduler/ folder where the main CMakeLists.txt is located;
- Wait for CMake parsing and configuration to complete;
- Build and run as a normal VS project.
CMake CLI
From root of the project:
mkdir build
cd build
cmake ../
Now can run the tests: ./test/test.
Useful tips (for clean project, from the build folder created above):
- Compiler switch:
- clang:
CC=clang CXX=clang++ cmake ../;
- GCC:
CC=gcc CXX=g++ cmake ../;
- Build type switch:
- Release, all optimizations, no debug info:
cmake -DCMAKE_BUILD_TYPE=Release ../;
- Release, all optimizations:
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo ../;
- Debug, no optimization at all:
cmake -DCMAKE_BUILD_TYPE=Debug ../;
Installation
mkdir build
cd build
# Your own install directory is optional.
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=$(pwd)/installed ../
make install
This creates a folder installed/ which contains the library binaries and headers.
Examples
A collection of some simple examples which also cover most of the usages.
One shot quick task
Use the scheduler as a thread pool for executing some simple functions.
(click to reveal)
TaskScheduler sched(name, threadCount, subQueueSize);
sched.Post(new Task([](Task* aTask) {
DoMyWork();
delete aTask;
}))
Multi-step task, coroutine
Task can be used as a coroutine which starts some async work on each step, gets a result on wakeup, makes next step, and repeats that until it ends and deletes self. Its context could be stored in a class or a struct. Or bound via lambda capturing. The example shows how a coroutine could send several HTTP requests one by one.
(click to reveal)
TaskScheduler sched(name, threadCount, subQueueSize);
class MyCoroutine
{
public:
MyCoroutine()
: myTask(this, &MyCoroutine::PrivStep1)
{
sched.Post(&myTask);
}
private:
void
PrivStep1(
Task* aTask)
{
assert(aTask == &myTask);
// When wakeup next time, do the next step.
myTask.SetCallback(this, &MyCoroutine::PrivStep2);
// Post self again when complete.
myClient.Get(firstUrl, [&sched, aTask]() {
sched.Post(aTask);
});
}
void
PrivStep2(
Task* aTask)
{
assert(aTask == &myTask);
// When wakeup next time, do the next step.
myTask.SetCallback(this, &MyCoroutine::PrivStep3);
// Post self again when complete.
myClient.Head(secondUrl, [&sched, aTask]() {
sched.Post(aTask);
});
}
void
PrivStep3(
Task* aTask)
{
assert(aTask == &myTask);
delete this;
}
HTTPClient myClient;
Task myTask;
};
new MyCoroutine();
Async work with a deadline
Task deadlines allow to implement any kinds of timeouts. For instance, send an HTTP request, and wakeup either when timeout happens or when the request is finished. The example uses task signal to demonstrate its most canonical purpose.
(click to reveal)
TaskScheduler sched(name, threadCount, subQueueSize);
class MyCoroutine
{
public:
MyCoroutine()
: myTask(this, &MyCoroutine::PrivStart)
{
sched.Post(&myTask);
}
private:
void
PrivStart(
Task* aTask)
{
assert(aTask == &myTask);
// When wakeup next time, check the result.
myTask.SetCallback(this, &MyCoroutine::PrivWait);
// The request should have a timeout 15 sec.
myTask.SetDelay(15 * 1000);
myClient.Get(someUrl, &myRequest, [&]() {
// Atomically wakeup + notify the task about request
// completion.
sched.Signal(&myTask);
});
// Start waiting.
sched.Post(&myTask);
}
void
PrivWait(
Task* aTask)
{
assert(aTask == &myTask);
if (myTask.ReceiveSignal())
{
// Completed!
printf("Result: %s\n", myRequest.ToString());
delete this;
return;
}
// Otherwise the only wakeup reason here could be that the
// deadline is due. Cancel the request so it completes
// faster and sends the signal.
assert(myTask.IsExpired());
myClient.Cancel(&myRequest);
// Continue the waiting.
sched.PostWait(&myTask);
}
HTTPClient myClient;
Request myRequest;
Task myTask;
};
new MyCoroutine();
Task as a long-living async work executor
Task can live for a long time to be used as a background worker. For example, send requests into the network or collect statistics for monitoring purposes. The example also shows the most typical usage of task wakeup.
(click to reveal)
TaskScheduler sched(name, threadCount, subQueueSize);
class MyConnection
{
public:
MyConnection()
: myTask(this, &MyConnection::PrivExecute)
{
sched.Post(&myTask);
}
void
Send(
Request* aRequest)
{
myQueue.Append(aRequest);
// Wakeup the task to let it know there is new work to do.
sched.Wakeup(&myTask);
}
private:
void
PrivExecute(
Task* aTask)
{
assert(aTask == &myTask);
// Execute all queued requests.
Request* req = myQueue.PopAll();
while (req != nullptr)
{
Request* next = req->myNext;
myClient.Put(req->myUrl, req->myData);
delete req;
req = next;
}
// Wait for more work.
sched.PostWait(&myTask);
}
HTTPClient myClient;
RequestQueue myQueue;
Task myTask;
};
MyConnection* conn = new MyConnection();
// Execute the requests in background.
conn->Send(new Request(url1, "some data1"));
conn->Send(new Request(url2, "some data2"));
Contribution
Contributions can be done via pull requests. There is no a strict list of code style rules, new code simply should resemble the existing code as close as possible. Each patch before sending it on a review should be tested on all supported compilers and operating systems. See the list of them above in dependencies. All features and bugfixes should have unit tests which pass, and the old unit tests also should pass.
Architecture overview
The scheduler is not a single monolithic algorithm. It is fused from several smaller ones. It is best to see them in the code with comments. Below is a short overview of the big picture.
Multi-Producer-Single-Consumer Queue
The scheduler receives tasks from the external code via a front queue. It is an unbounded lock-free MPSC queue. See src\mg\common\MultiProducerQueueIntrusive.h.
Push is an atomic compare-exchange which in case of simultaneous access by multiple threads is retried. No spinlocks, nor any mutexes.
Pop is only able to take all the tasks at once and the order is reversed. That is the price of it being lock-free, a single atomic exchange. Basically, this queue is a stack, not a list. The order is restored back to normal when the scheduler processes the popped items.
Multi-Consumer-Single-Producer Queue
This is a backend queue of the scheduler. From here the worker threads pick up the tasks ready for execution. It is an unbounded semi-lock-free MCSP queue. See src\mg\common\MultiConsumerQueue.h.
There is no a simple well known algorithm for having multiple consumers which would be at the same time wait-free; lock-free; unbounded; and with ability to pop items one by one. Mostly that is because of the ABA problem of concurrent algorithms. Working them around usually is quite untrivial and can cost notable fraction of performance.
The MCSP queue presented here makes a compromise. It is semi-lock-free. Meaning that it has a mutex, but it is taken extremely rarely. Moreover, the algorithm parameters allow to control the lock frequency.
How it works is that in essence the queue is a mutex-protected list of lock-free bounded queues. Lock-free bounded queue is quite easy to implement both for multi-consumer and for multi-producer cases. To drop the limits it is enough to have an unlimited list of such bounded queues, a list of blocks.
The consumers, when attach to the queue, under a lock remember the current read-position in this list, and then consume the saved block in a lock-free way one item by one. When the block is exhausted, they switch to a next block again under a mutex.
The producer works in a similar way - it remembers the block-list tail, pushes new items into it in a lock-free way, and when it becomes full, the producer appends a new block under a lock.
The critical section here (protected by the mutex) is very narrow - just a switch of a few pointers. What is even better, it depends on block size. The bigger are these lock-free sub-queues, the rarer the lock is taken. For example, if sub-queue size is 10000, then the lock is taken once per 10000 pops.
An example of how the queue can look:
mutex-protected
links
popped ____ write
items / \ position
+v-v-v----+ +---------+ +---------+ +--v------+
| | --> | x x x| -> |x x x x x| -> |x - - - -|
+--- ^----+ +----^----+ +---------+ +---------+
consumer1 consumer2 \___________/
position position write block
- Here the queue has 4 blocks (sub-queues);
- Each sub-queue has size 5 (can do 5 lock-free pops until need to lock the mutex);
- The links between the blocks are protected by a mutex;
- There are 2 consumers. One of them is a bit behind. It will catch up on next pop;
- The last block is for new items. It has space for 4 more items.
Compared to a trivial queue which would take a mutex lock on each pop and push, this MCSP queue under extreme contention is faster up to x10 times according to benchmarks. For reference one can run tests and observe the output to find out how it performs on various hardware.