// ThreadPool.cpp #include #include #include #include #include "ThreadPool.h" #include "../Logger/Logger.h" #include "../Utilities/Utilities.h" using Show = StaticLogger<0>; using DebugLog = StaticLogger<1>; ThreadPool::ThreadPool(size_t n) { CallObj threadProc = [this]() { while (true) { CallObj* pCo = Q_.deQ(); if (pCo == nullptr) { DebugLog::write("\n--deQed nullptr in ThreadPool"); Q_.enQ(nullptr); break; } (*pCo)(); delete pCo; // this is a copy on heap so delete } DebugLog::write( "\n thread " + Utilities::Converter::toString(std::this_thread::get_id()) + " terminating" ); }; for (size_t i = 0; i < n; ++i) { std::thread t(threadProc); threads_.push_back(std::move(t)); DebugLog::write( "\n--starting threadpool thread " + Utilities::Converter::toString(t.get_id()) ); } } void ThreadPool::workItem(CallObj* pCo) { if (pCo == nullptr) { DebugLog::write("\n enqueuing nullptr in threadpool"); Q_.enQ(pCo); return; } CallObj* pCnew = new CallObj(*pCo); // make copy as orig may change Q_.enQ(pCnew); DebugLog::write( "\n--threadpool queue size = " + Utilities::Converter::toString(Q_.size()) ); } void ThreadPool::wait() { DebugLog::write( "\n entering wait with queue size = " + Utilities::Converter::toString(Q_.size()) ); for (auto& thrd : threads_) thrd.join(); DebugLog::write( "\n--leaving wait with queue size = " + Utilities::Converter::toString(Q_.size()) ); } ThreadPool::~ThreadPool() { for (auto& thrd : threads_) { if (thrd.joinable()) thrd.join(); } } //----< test stub >-------------------------------------------------- #ifdef TEST_THREADPOOL #include using namespace std::chrono_literals; using namespace Utilities; using Utils = StringHelper; int main() { Show::attach(&std::cout); Show::start(); DebugLog::attach(&std::cout); //DebugLog::start(); Utils::Title("Testing ThreadPool"); ThreadPool trpl(8); ThreadPool::CallObj co = [&trpl]() { Show::write( "\n hello from thread " + Utilities::Converter::toString(std::this_thread::get_id()) ); }; for (size_t i = 0; i < 20; ++i) trpl.workItem(&co); trpl.workItem(nullptr); trpl.wait(); //std::cout << "\n\n"; } #endif