Add event loop with thread pool
I think it works Signed-off-by: King_DuckZ <king_duckz@gmx.com>
This commit is contained in:
parent
e3b8b563f0
commit
d44529871c
4 changed files with 104 additions and 3 deletions
78
src/evloop.cpp
Normal file
78
src/evloop.cpp
Normal file
|
@ -0,0 +1,78 @@
|
|||
#include "evloop.hpp"
|
||||
#include <ev++.h>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include <algorithm>
|
||||
#include <random>
|
||||
#include <functional>
|
||||
#include <taskflow/taskflow.hpp>
|
||||
#include <string>
|
||||
|
||||
namespace duck {
|
||||
namespace {
|
||||
auto time_rand = std::bind(std::uniform_int_distribution<int>(2, 8), std::mt19937(std::time(0)));
|
||||
|
||||
class HtmlFetchTimer : public ev::timer {
|
||||
public:
|
||||
HtmlFetchTimer (ev::loop_ref& loop, tf::Subflow* subflow, std::string&& url) :
|
||||
m_subflow(subflow),
|
||||
m_url(std::move(url))
|
||||
{
|
||||
this->set(loop);
|
||||
this->set<HtmlFetchTimer, &HtmlFetchTimer::on_timer>(this);
|
||||
}
|
||||
|
||||
void on_timer() {
|
||||
m_subflow->emplace([this]() {std::cout << "Timer elapsed for " << m_url << "!\n";});
|
||||
}
|
||||
|
||||
void start (double delay) {
|
||||
ev::timer::start(delay, 0.0);
|
||||
}
|
||||
|
||||
private:
|
||||
tf::Subflow* m_subflow;
|
||||
std::string m_url;
|
||||
};
|
||||
|
||||
class EvThreadPool {
|
||||
public:
|
||||
typedef std::thread thread_t;
|
||||
EvThreadPool() :
|
||||
m_loop(ev::AUTO)
|
||||
{
|
||||
}
|
||||
|
||||
void start() {
|
||||
m_taskflow.emplace([this](tf::Subflow& subflow){main_loop(subflow);});
|
||||
m_executor.run(m_taskflow);
|
||||
}
|
||||
|
||||
void join() {
|
||||
m_executor.wait_for_all();
|
||||
std::cout << "all tasks completed\n";
|
||||
}
|
||||
|
||||
private:
|
||||
void main_loop (tf::Subflow& subflow) {
|
||||
m_timer = std::make_unique<HtmlFetchTimer>(m_loop, &subflow, "lalalala");
|
||||
m_timer->start(static_cast<double>(time_rand()));
|
||||
|
||||
this->m_loop.run(0);
|
||||
}
|
||||
|
||||
ev::default_loop m_loop;
|
||||
tf::Taskflow m_taskflow;
|
||||
tf::Executor m_executor;
|
||||
std::unique_ptr<HtmlFetchTimer> m_timer;
|
||||
};
|
||||
} //unnamed namespace
|
||||
|
||||
void test() {
|
||||
//const auto processor_count = std::thread::hardware_concurrency();
|
||||
EvThreadPool worker; //(std::max(2U, processor_count) - 1);
|
||||
worker.start();
|
||||
worker.join();
|
||||
}
|
||||
} //namespace duck
|
Loading…
Add table
Add a link
Reference in a new issue