Skip to content

Instantly share code, notes, and snippets.

@paxbun
Created November 9, 2019 04:18
Show Gist options
  • Save paxbun/a5fe91a63146b5caa634a639aa1d6e21 to your computer and use it in GitHub Desktop.
Save paxbun/a5fe91a63146b5caa634a639aa1d6e21 to your computer and use it in GitHub Desktop.
Simple thread pool implementation with C++17 standard libraries
#include "ThreadPool.hh"
void ThreadPool::Run()
{
_threads.reserve(_numThreads);
for (size_t i = 0; i < _numThreads; ++i)
_threads.push_back(std::thread(std::bind(&ThreadPool::_Thread, this)));
}
void ThreadPool::Stop(bool wait_for_remaining_tasks)
{
_terminated = true;
if (!wait_for_remaining_tasks)
{
std::unique_lock lock(_taskMutex);
_tasks.clear();
}
_cv.notify_all();
for (auto& th : _threads) th.join();
}
void ThreadPool::Post(std::function<void()> func)
{
std::unique_lock lock(_taskMutex);
_tasks.push_back(func);
_cv.notify_one();
}
void ThreadPool::_Thread()
{
while (true)
{
auto func = _Get();
if (!func)
return;
func();
}
}
std::function<void()> ThreadPool::_Get()
{
std::unique_lock lock(_taskMutex);
while (_tasks.empty())
{
if (_terminated)
return std::function<void()>();
_cv.wait(lock);
}
auto rtn = std::move(_tasks.front());
_tasks.pop_front();
return rtn;
}
#include <atomic>
#include <condition_variable>
#include <deque>
#include <functional>
#include <mutex>
#include <thread>
#include <vector>
class ThreadPool
{
private:
std::vector<std::thread> _threads;
std::size_t _numThreads;
std::condition_variable _cv;
std::deque<std::function<void()>> _tasks;
std::mutex _taskMutex;
std::atomic_bool _terminated;
public:
ThreadPool(std::size_t size) : _numThreads(size), _terminated(false) {}
public:
void Run();
void Stop(bool wait_for_remaining_tasks = false);
void Post(std::function<void()> func);
private:
void _Thread();
std::function<void()> _Get();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment