-
-
Save jitpaul/b7f422c4c638a0647143a07363647132 to your computer and use it in GitHub Desktop.
Multithreading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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