2020-08-01 07:02:54 +02:00
|
|
|
#include "evloop.hpp"
|
|
|
|
#include <ev++.h>
|
|
|
|
#include <thread>
|
|
|
|
#include <vector>
|
|
|
|
#include <iostream>
|
|
|
|
#include <algorithm>
|
|
|
|
#include <random>
|
|
|
|
#include <functional>
|
|
|
|
#include <string>
|
|
|
|
|
|
|
|
namespace duck {
|
|
|
|
namespace {
|
|
|
|
auto time_rand = std::bind(std::uniform_int_distribution<int>(2, 8), std::mt19937(std::time(0)));
|
|
|
|
|
2020-08-01 07:24:45 +02:00
|
|
|
class HtmlFetchTimer : public EvTimerTask {
|
2020-08-01 07:02:54 +02:00
|
|
|
public:
|
|
|
|
HtmlFetchTimer (ev::loop_ref& loop, tf::Subflow* subflow, std::string&& url) :
|
2020-08-01 07:24:45 +02:00
|
|
|
EvTimerTask(static_cast<double>(time_rand()), loop, subflow),
|
2020-08-01 07:02:54 +02:00
|
|
|
m_url(std::move(url))
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2020-08-01 07:24:45 +02:00
|
|
|
virtual void on_timer() override {
|
|
|
|
subflow().emplace([this]() {std::cout << "Timer elapsed for " << m_url << "!\n";});
|
2020-08-01 07:02:54 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
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");
|
|
|
|
|
|
|
|
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
|
|
|
|
|
2020-08-01 07:24:45 +02:00
|
|
|
EvTimerTask::EvTimerTask (double delay, ev::loop_ref& loop, tf::Subflow* subflow) :
|
|
|
|
m_subflow(subflow)
|
|
|
|
{
|
|
|
|
this->set(loop);
|
|
|
|
this->set<EvTimerTask, &EvTimerTask::on_timer_ev>(this);
|
|
|
|
ev::timer::start(delay, 0.0);
|
|
|
|
}
|
|
|
|
|
|
|
|
tf::Subflow& EvTimerTask::subflow() {
|
|
|
|
return *m_subflow;
|
|
|
|
}
|
|
|
|
|
|
|
|
void EvTimerTask::on_timer_ev() {
|
|
|
|
this->on_timer();
|
|
|
|
}
|
|
|
|
|
2020-08-01 07:02:54 +02:00
|
|
|
void test() {
|
|
|
|
//const auto processor_count = std::thread::hardware_concurrency();
|
|
|
|
EvThreadPool worker; //(std::max(2U, processor_count) - 1);
|
|
|
|
worker.start();
|
|
|
|
worker.join();
|
|
|
|
}
|
|
|
|
} //namespace duck
|