Skip to content

Commit

Permalink
[add] add threadpool interface
Browse files Browse the repository at this point in the history
Signed-off-by: tsymiar <[email protected]>
  • Loading branch information
tsymiar committed Dec 22, 2024
1 parent 58f4c5d commit ebd95f2
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/utils/TaskBase.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#ifndef TASKBASE_H
#define TASKBASE_H

class TaskBase {
public:
virtual ~TaskBase() = default;
virtual void execute() = 0;
};

#endif // TASKBASE_H
48 changes: 48 additions & 0 deletions src/utils/threadpool.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include "threadpool.h"

threadpool::threadpool() : m_stopPool(false) { }

threadpool::~threadpool() { }

void threadpool::start(size_t threadsnum)
{
for (size_t i = 0; i < threadsnum; ++i) {
m_workers.emplace_back([this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->m_queueMutex);
this->m_condition.wait(lock, [this] { return this->m_stopPool || !this->m_tasks.empty(); });
if (this->m_stopPool && this->m_tasks.empty()) {
return;
}
task = std::move(this->m_tasks.front());
this->m_tasks.pop();
}
task();
}
});
}
}

template<class F>
void threadpool::enqueue(F&& f)
{
{
std::unique_lock<std::mutex> lock(m_queueMutex);
m_tasks.emplace(std::forward<F>(f));
}
m_condition.notify_one();
}

void threadpool::stop()
{
{
std::unique_lock<std::mutex> lock(m_queueMutex);
m_stopPool = true;
}
m_condition.notify_all();
for (std::thread& worker : m_workers) {
worker.join();
}
}
31 changes: 31 additions & 0 deletions src/utils/threadpool.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#ifndef THREADPOOL_H
#define THREADPOOL_H

#include <vector>
#include <queue>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <atomic>

class threadpool {
public:
threadpool();
~threadpool();

template<class F>
void enqueue(F&& f);

void start(size_t threadsnum);
void stop();

private:
std::vector<std::thread> m_workers;
std::queue<std::function<void()>> m_tasks;
std::mutex m_queueMutex;
std::condition_variable m_condition;
std::atomic<bool> m_stopPool;
};

#endif // THREADPOOL_H

0 comments on commit ebd95f2

Please sign in to comment.