Simple threading facilities for C++, inspired by the book by Williams
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

39 lines
768 B

#pragma once
/* Simple thread pool, no fancy stuff.
It is thread safe (i.e. concurrent adds).
Threads terminate if there is no work (we need wait_and_pop for that).
Works best if all work is added, and then run.
Doesn't care about exceptions.
*/
#include <vector>
#include <functional>
#include <thread>
#include "lock_queue.hpp"
struct thread_pool {
void add(std::function<void()> f){
work.push(f);
}
void run(int number_of_threads){
for(int i = 0; i < number_of_threads; ++i){
threads.emplace_back([this]{
auto x = work.try_pop();
while(x){
(*x)();
x = work.try_pop();
}
});
}
}
~thread_pool(){
for(auto & t : threads) t.join();
}
private:
queue<std::function<void()>> work;
std::vector<std::thread> threads;
};