added tests for threads pool

This commit is contained in:
cryptozoidberg 2022-02-08 13:59:09 +01:00
parent be318d6ed4
commit e2bb37e5cb
No known key found for this signature in database
GPG key ID: 22DEB97A54C6FDEC
2 changed files with 35 additions and 7 deletions

View file

@ -16,7 +16,7 @@ namespace utils
virtual void execute()=0;
};
template<class t_executor_func>
template<typename t_executor_func>
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<t_executor_func>
template<typename t_executor_func>
std::shared_ptr<call_executor_base> build_call_executor(t_executor_func func)
{
std::shared_ptr<call_executor_base> res = new call_executor_t<t_executor_func>(func);
std::shared_ptr<call_executor_base> res(static_cast<call_executor_base*>(new call_executor_t<t_executor_func>(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<t_executor_func>
template<typename t_executor_func>
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<std::thread> m_threads;
atomic<bool> m_is_stop;
std::atomic<bool> m_is_stop;
std::atomic<int64_t> m_threads_counter;
};
}

View file

@ -6,10 +6,27 @@
#include <string>
#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<uint64_t> 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");
}