Store std::thread in worker thread class by value and explicitly start it up, and don't use shared_ptr in thread pools

This commit is contained in:
Silent committed 2019-08-11 14:03:53 +02:00
1 parent 34109afb2d
commit 1a992bf023
2 files changed
+17 -16

No files matched your search

+11 -10
View File
@@ -1,20 +1,23 @@
#include "base/logging.h"
#include "thread/threadpool.h"
#include "thread/threadutil.h"
#include "Common/MakeUnique.h"
///////////////////////////// WorkerThread
WorkerThread::WorkerThread() {
thread.reset(new std::thread(std::bind(&WorkerThread::WorkFunc, this)));
}
WorkerThread::~WorkerThread() {
{
std::lock_guard<std::mutex> guard(mutex);
active = false;
signal.notify_one();
}
thread->join();
if (thread.joinable()) {
thread.join();
}
}
void WorkerThread::StartUp() {
thread = std::thread(std::bind(&WorkerThread::WorkFunc, this));
}
void WorkerThread::Process(std::function<void()> work) {
@@ -50,10 +53,6 @@ void WorkerThread::WorkFunc() {
}
}
LoopWorkerThread::LoopWorkerThread() : WorkerThread(true) {
thread.reset(new std::thread(std::bind(&LoopWorkerThread::WorkFunc, this)));
}
void LoopWorkerThread::Process(std::function<void(int, int)> work, int start, int end) {
std::lock_guard<std::mutex> guard(mutex);
work_ = std::move(work);
@@ -99,7 +98,9 @@ ThreadPool::ThreadPool(int numThreads) {
void ThreadPool::StartWorkers() {
if (!workersStarted) {
for(int i = 0; i < numThreads_; ++i) {
workers.push_back(std::make_shared<LoopWorkerThread>());
auto workerPtr = make_unique<LoopWorkerThread>();
workerPtr->StartUp();
workers.push_back(std::move(workerPtr));
}
workersStarted = true;
}