Skip to content

Instantly share code, notes, and snippets.

@jitpaul

jitpaul/threadpool.cpp Secret

Created Feb 17, 2020
Embed
What would you like to do?
Multithreading
#include <iostream>
#include <functional>
#include <mutex>
#include <thread>
#include <vector>
#include <queue>
#include <atomic>
class Threadpool
{
std::queue<std::function<void()>> d_queue;
std::vector<std::shared_ptr<std::thread>> d_threads;
int d_numThreads;
int d_queueSize;
std::mutex d_mutex;
std::atomic<bool> d_stopFlag;
public:
Threadpool(int threads, int s);
bool start();
bool stop();
int enqueue(std::function<void()> func);
private:
void execute();
};
Threadpool::Threadpool(int threads, int s) : d_numThreads(threads), d_queueSize(s) {}
int Threadpool::enqueue(std::function<void()> func)
{
std::lock_guard<std::mutex> lg(d_mutex);
if (d_queue.size() == d_queueSize)
{
return 1;
}
d_queue.push(func);
return 0;
}
bool Threadpool::start()
{
for (int i = 0; i < d_numThreads; ++i)
{
std::shared_ptr<std::thread> sp(new std::thread(&Threadpool::execute, this));
d_threads.push_back(sp);
}
}
bool Threadpool::stop()
{
d_stopFlag = true;
for (auto sp : d_threads)
{
sp->join();
}
}
void Threadpool::execute()
{
std::function<void()> job;
while (!d_stopFlag)
{
{
std::lock_guard<std::mutex> lg(d_mutex);
job = d_queue.front();
d_queue.pop();
}
job();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment