diff --git a/CMakeLists.txt b/CMakeLists.txt index 67d96eb2..ffd682b3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,7 @@ endif() project(PIP) set(PIP_MAJOR 4) set(PIP_MINOR 7) -set(PIP_REVISION 1) +set(PIP_REVISION 2) set(PIP_SUFFIX ) set(PIP_COMPANY SHS) set(PIP_DOMAIN org.SHS) diff --git a/libs/main/thread/pithreadpoolloop.cpp b/libs/main/thread/pithreadpoolloop.cpp index 1e364e4a..b8e1494f 100644 --- a/libs/main/thread/pithreadpoolloop.cpp +++ b/libs/main/thread/pithreadpoolloop.cpp @@ -106,16 +106,29 @@ PIThreadPoolLoop::PIThreadPoolLoop(int thread_cnt) { if (thread_cnt <= 0) thread_cnt = piMaxi(1, PISystemInfo::instance()->processorsCount); piForTimes(thread_cnt) { - auto * t = new PIThread(); + auto * t = new PIThread([this]() { + while (true) { + sem_exec.acquire(); + if (is_destroy) return; + int cc = counter.fetch_add(1); + func(cc); + sem_done.release(); + } + }); threads << t; } + for (auto * t: threads) + t->start(); // piCout << "PIThreadPoolLoop" << proc_cnt << "threads"; } PIThreadPoolLoop::~PIThreadPoolLoop() { - for (auto * t: threads) { + is_destroy = true; + for (auto * t: threads) t->stop(); + sem_exec.release(threads.size()); + for (auto * t: threads) { if (!t->waitForFinish(100_ms)) t->terminate(); delete t; } @@ -127,20 +140,19 @@ void PIThreadPoolLoop::setFunction(std::function f) { } +void PIThreadPoolLoop::wait() { + // piCout << "wait" << wait_count; + if (wait_count <= 0) return; + sem_done.acquire(wait_count); + wait_count = 0; + // piCout << "wait done"; +} + + void PIThreadPoolLoop::start(int index_start, int index_count) { - counter = index_start; - int end = index_start + index_count; - for (auto * t: threads) - t->start([this, end, t]() { - while (1) { - int cc = counter.fetch_add(1); - if (cc >= end) { - t->stop(); - return; - } - func(cc); - } - }); + counter = index_start; + wait_count = index_count; + sem_exec.release(index_count); } @@ -154,9 +166,3 @@ void PIThreadPoolLoop::exec(int index_start, int index_count, std::functionwaitForFinish(); -} diff --git a/libs/main/thread/pithreadpoolloop.h b/libs/main/thread/pithreadpoolloop.h index 0dbbb606..d79af806 100644 --- a/libs/main/thread/pithreadpoolloop.h +++ b/libs/main/thread/pithreadpoolloop.h @@ -26,6 +26,7 @@ #ifndef PITHREADPOOLLOOP_H #define PITHREADPOOLLOOP_H +#include "pisemaphore.h" #include "pivector.h" class PIThread; @@ -83,7 +84,9 @@ public: private: PIVector threads; std::function func; - std::atomic_int counter = {0}; + PISemaphore sem_exec, sem_done; + std::atomic_bool is_destroy = {false}; + std::atomic_int counter = {0}, wait_count = {0}; };