diff --git a/src/common/threads_pool.h b/src/common/threads_pool.h index b30e7b57..b1d4aebc 100644 --- a/src/common/threads_pool.h +++ b/src/common/threads_pool.h @@ -16,7 +16,7 @@ namespace utils virtual void execute()=0; }; - template + template struct call_executor_t : public call_executor_base { call_executor_t(t_executor_func f) :m_func(f) @@ -28,15 +28,16 @@ namespace utils } }; - template + template std::shared_ptr build_call_executor(t_executor_func func) { - std::shared_ptr res = new call_executor_t(func); + std::shared_ptr res(static_cast(new call_executor_t(func))); return res; } class threads_pool { + public: void init() { m_is_stop = false; @@ -44,14 +45,14 @@ namespace utils for (int i = 0; i < num_threads; i++) { - m_threads.push_back(std::thread(worker_func)); + m_threads.push_back(std::thread([this](){this->worker_func(); })); } } threads_pool(): m_is_stop(false), m_threads_counter(0) {} - template + template bool add_job(t_executor_func func) { { @@ -62,6 +63,16 @@ namespace utils return true; } + ~threads_pool() + { + m_is_stop = true; + m_condition.notify_all(); + for (auto& th : m_threads) + { + th.join(); + } + } + private: void worker_func() { @@ -96,7 +107,7 @@ namespace utils std::condition_variable m_condition; std::mutex m_queue_mutex; std::vector m_threads; - atomic m_is_stop; + std::atomic m_is_stop; std::atomic m_threads_counter; }; } \ No newline at end of file diff --git a/tests/performance_tests/threads_pool_tests.h b/tests/performance_tests/threads_pool_tests.h index 2494dae8..a1bf2042 100644 --- a/tests/performance_tests/threads_pool_tests.h +++ b/tests/performance_tests/threads_pool_tests.h @@ -6,10 +6,27 @@ #include #include "include_base_utils.h" -#include "threads_pool.h" +#include "common/threads_pool.h" inline void thread_pool_tests() { + { + utils::threads_pool pool; + pool.init(); + std::atomic count_jobs_finished = 0; + size_t i = 0; + for (; i != 10; i++) + { + pool.add_job([&, i]() {LOG_PRINT_L0("Job " << i << " started"); epee::misc_utils::sleep_no_w(10000); ++count_jobs_finished; LOG_PRINT_L0("Job " << i << " finished"); }); + } + while (count_jobs_finished != i) + { + epee::misc_utils::sleep_no_w(500); + } + LOG_PRINT_L0("All jobs finished"); + } + LOG_PRINT_L0("Scope left"); + } \ No newline at end of file