79 lines
1.7 KiB
C++
79 lines
1.7 KiB
C++
|
#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
|