An ultra-simple thread pool implementation for running void() functions in multiple worker threads

void_thread_pool.cpp

© 2021 Dr Sebastien Sikora.

[email protected]

Updated 06/11/2021.

What is it?

void_thread_pool.cpp is an ultra-simple thread pool implementation for running functions that return void in multiple worker threads.

It is a synthesis of the brilliantly helpful code snippets and examples by users phd-ap-ece and pio here. Useful supplementary information found here. Explanation of the syntax [this]() { ... } for the predicate second argument to std::condition_variable.wait() found here.

How to use it?

Say we have a function, or a class with a member function that returns void, that we would like to call in it's own thread.

void FooBar1() {
	std::string message = "FooBar1 call.\n";
	std::cout << message;
}

void FooBar2(int id) {
	std::string message = "My id is " + std::to_string(id) + "\n";
	std::cout << message;
}

class Foo {
	private:
		int m_id = 0;
	public:
		Foo(int id) { m_id = id; }
		~Foo() { }
		void Bar(void) { *** Stuff happens *** }
};

First we instantiate the thread pool.

VoidThreadPool thread_pool(true);

// Optional first argument set to true prints pool messages to the console.

VoidThreadPool thread_pool(true, 8)

// If we don't specify the optional second number_of_workers argument it defaults to the
// thread count returned by std::thread::hardware_concurrency().

Now, to queue a job for solution, we add it to the thread pool job queue using the thread pool's AddJob() member function.

thread_pool.AddJob(FooBar1);
thread_pool.AddJob(&FooBar1);

// We can pass the function by reference to avoid making a copy.

thread_pool.AddJob(std::bind(&FooBar2, i));

// If we need to pass arguments with the function we encapsulate both using std::bind.

Foo a_foo;

thread_pool.AddJob(std::bind(&Foo::Bar, a_foo));

// If we want to pass a class member function, we again use std::bind to encapsulate a
// pointer to a member function of the class, followed by an instance of that class.

thread_pool.AddJob(std::bind(&Foo::Bar, &a_foo));

// We can pass the class instance by reference, otherwise std::bind will make a copy of the
// object. However, we are then taking responsibility for making sure the referenced object
// still exists for the duration of the thread's execution.

Worker threads will begin to execute jobs as soon as they are added to the queue. If we need to wait for all jobs added to the queue to be completed prior to doing something else, we call the thread pool's WaitForAllJobs() member function. This will return when the job queue is empty and all running jobs are completed.

To stop the thread pool, we call it's Finish() method, which will stop the worker threads once all currently queued jobs are completed. deleteing a VoidThreadPool via a pointer to call it's destructor will first call Finish().

For a complete usage example see demo.cpp.

To compile the example (for example, using gcc), enter g++ -o main -g void_thread_pool.cpp demo.cpp on the command line.

License:

Mit License Logo

void_thread_pool.cpp is distributed under the terms of the MIT license. Learn about the MIT license here

Owner
Seb Sikora
Software and Embedded Hardware developer
Seb Sikora
Similar Resources

High Performance Linux C++ Network Programming Framework based on IO Multiplexing and Thread Pool

Kingpin is a C++ network programming framework based on TCP/IP + epoll + pthread, aims to implement a library for the high concurrent servers and clie

Oct 19, 2022

Work Stealing Thread Pool

wstpool Work Stealing Thread Pool, Header Only, C++ Threads Consistent with the C++ async/future programming model. Drop-in replacement for 'async' fo

Oct 29, 2022

MAN - Man is Thread Pool in C++17

Introduction MAN is a ThreadPool wrote in C++17. The name is chosen because, at least in France, it is said that men are not able to do several things

Mar 6, 2022

ThreadPool - A fastest, exception-safety and pure C++17 thread pool.

Warnings Since commit 468129863ec65c0b4ede02e8581bea682351a6d2, I move ThreadPool to C++17. (To use std::apply.) In addition, the rule of passing para

Dec 28, 2022

CTPL - Modern and efficient C++ Thread Pool Library

CTPL Modern and efficient C++ Thread Pool Library A thread pool is a programming pattern for parallel execution of jobs, http://en.wikipedia.org/wiki/

Dec 22, 2022

A novel technique to communicate between threads using the standard ETHREAD structure

A novel technique to communicate between threads using the standard ETHREAD structure

🕵️ dearg-thread-ipc-stealth Usage There are two main exported methods, one to read from another thread, and another to serve the content to another t

Nov 10, 2022

Parallel algorithms (quick-sort, merge-sort , enumeration-sort) implemented by p-threads and CUDA

程序运行方式 一、编译程序,进入sort-project(cuda-sort-project),输入命令行 make 程序即可自动编译为可以执行文件sort(cudaSort)。 二、运行可执行程序,输入命令行 ./sort 或 ./cudaSort 三、删除程序 make clean 四、指定线程

May 30, 2022

Objectpool - Object pool implementation in C++11

Object pool allocator This is a C++11 implementation of an object pool allocator. For more information on object pool allocators and their purpose see

Nov 3, 2022

Simple and fast C library implementing a thread-safe API to manage hash-tables, linked lists, lock-free ring buffers and queues

libhl C library implementing a set of APIs to efficiently manage some basic data structures such as : hashtables, linked lists, queues, trees, ringbuf

Dec 3, 2022
Thread pool - Thread pool using std::* primitives from C++17, with optional priority queue/greenthreading for POSIX.

thread_pool Thread pool using std::* primitives from C++11. Also includes a class for a priority thread pool. Requires concepts and C++17, including c

Dec 30, 2022
Thread-pool-cpp - High performance C++11 thread pool

thread-pool-cpp It is highly scalable and fast. It is header only. No external dependencies, only standard library needed. It implements both work-ste

Dec 17, 2022
ThreadPool - A simple C++11 Thread Pool implementation

ThreadPool A simple C++11 Thread Pool implementation. Basic usage: // create thread pool with 4 worker threads ThreadPool pool(4); // enqueue and sto

Jan 7, 2023
A modern thread pool implementation based on C++20
A modern thread pool implementation based on C++20

thread-pool A simple, functional thread pool implementation using pure C++20. Features Built entirely with C++20 Enqueue tasks with or without trackin

Dec 22, 2022
Pool is C++17 memory pool template with different implementations(algorithms)

Object Pool Description Pool is C++17 object(memory) pool template with different implementations(algorithms) The classic object pool pattern is a sof

Nov 18, 2022
A easy to use multithreading thread pool library for C. It is a handy stream like job scheduler with an automatic garbage collector. This is a multithreaded job scheduler for non I/O bound computation.

A easy to use multithreading thread pool library for C. It is a handy stream-like job scheduler with an automatic garbage collector for non I/O bound computation.

Jun 4, 2022
A C++17 thread pool for high-performance scientific computing.

We present a modern C++17-compatible thread pool implementation, built from scratch with high-performance scientific computing in mind. The thread pool is implemented as a single lightweight and self-contained class, and does not have any dependencies other than the C++17 standard library, thus allowing a great degree of portability

Jan 4, 2023
An easy to use C++ Thread Pool

mvThreadPool (This library is available under a free and permissive license) mvThreadPool is a simple to use header only C++ threadpool based on work

Dec 8, 2022
EOSP ThreadPool is a header-only templated thread pool writtent in c++17.

EOSP Threadpool Description EOSP ThreadPool is a header-only templated thread pool writtent in c++17. It is designed to be easy to use while being abl

Apr 22, 2022