93 lines
2.3 KiB
C++
93 lines
2.3 KiB
C++
#include "Quickbus.h"
|
|
|
|
#include "lib/quickbus/routing/Router.h"
|
|
#include "lib/quickbus/network/QBConnectionManager.h"
|
|
#include "lib/config/protos/quickbus_cfg.pb.h"
|
|
#include "lib/os/os.h"
|
|
#include "lib/utils/bts_assert.h"
|
|
|
|
#include <boost/asio.hpp>
|
|
#include <thread>
|
|
|
|
namespace bts {
|
|
namespace qbus {
|
|
|
|
struct Quickbus::PImpl
|
|
{
|
|
PImpl(config::QuickbusNodeCfg const&cfg,ThreadOptions options) :
|
|
io_service(),
|
|
router(make_node_id()),
|
|
connection_manager(io_service,router,cfg),
|
|
worker(),
|
|
thread_options(options),
|
|
do_work_tid()
|
|
{}
|
|
boost::asio::io_service io_service;
|
|
Router router;
|
|
QBConnectionManager connection_manager;
|
|
std::unique_ptr<std::thread> worker;
|
|
ThreadOptions thread_options;
|
|
std::thread::id do_work_tid;
|
|
};
|
|
|
|
Quickbus::Quickbus(ThreadOptions options) :
|
|
me (new PImpl(config::QuickbusNodeCfg(),options))
|
|
{init();}
|
|
|
|
Quickbus::Quickbus(config::QuickbusNodeCfg const&cfg, ThreadOptions options) :
|
|
me (new PImpl(cfg,options))
|
|
{init();}
|
|
|
|
Quickbus::~Quickbus ()
|
|
{
|
|
me->io_service.stop();
|
|
if (me->worker)
|
|
me->worker->join();
|
|
}
|
|
|
|
bool Quickbus::on_qb_thread() const
|
|
{
|
|
if (me->worker)
|
|
return std::this_thread::get_id() == me->worker->get_id();
|
|
else
|
|
return std::this_thread::get_id() == me->do_work_tid;
|
|
}
|
|
|
|
void Quickbus::post (std::function<void()> const &action,uint32_t delay_ms)
|
|
{
|
|
if (delay_ms == 0) {
|
|
me->io_service.post(action);
|
|
}
|
|
else {
|
|
std::shared_ptr<boost::asio::deadline_timer> timer = std::make_shared<boost::asio::deadline_timer>(me->io_service);
|
|
timer->expires_from_now(boost::posix_time::milliseconds(delay_ms));
|
|
timer->async_wait([timer, action](boost::system::error_code const& err) { if (!err) action(); });
|
|
}
|
|
}
|
|
|
|
Router& Quickbus::router() const
|
|
{return me->router;}
|
|
|
|
void Quickbus::init()
|
|
{
|
|
if (me->thread_options == ThreadOptions::own_thread) {
|
|
me->worker = std::make_unique<std::thread> (std::thread ([this] () {
|
|
os::set_thread_name("quickbus");
|
|
me->io_service.run();
|
|
}));
|
|
me->do_work_tid = me->worker->get_id();
|
|
}
|
|
else
|
|
me->do_work_tid = std::this_thread::get_id() ;
|
|
}
|
|
|
|
bool Quickbus::do_work()
|
|
{
|
|
bts_assert(me->thread_options == ThreadOptions::outside_thread);
|
|
me->do_work_tid = std::this_thread::get_id();
|
|
return me->io_service.poll();
|
|
}
|
|
|
|
}}
|
|
|