所以我练习了升级库并且遇到了困难。我的应用程序使用asio :: serial_port,我决定添加一些日志功能。这就出现了问题。
当我为asio :: io_service
创建线程时boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service_));
然后尝试使用
记录某些内容 BOOST_LOG_SEV(MBLog::get(), logging::trivial::trace) << "something to trace;"
之前打电话
port_->async_read_some(
boost::asio::buffer(read_buf_raw_, SERIAL_PORT_READ_BUF_SIZE),
boost::bind(
&SerialPort::on_receive_,
this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
然后处理程序on_receive_
永远不会被调用(端口仍然可以写write_some
thow)。当记录宏被注释掉或在执行async_read_some
之后完成时,它神奇地起作用。我想知道这背后的魔力是什么,或者从哪里开始寻找答案?也许有些人已经知道问题然后请分享。其他有用的信息:
我正在使用 MSVC2017 。
提升日志初始化
Logger.h
#define _HAS_AUTO_PTR_ETC 1
#include <boost/log/trivial.hpp>
#include <boost/log/sources/global_logger_storage.hpp>
namespace logging = boost::log;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;
namespace attrs = boost::log::attributes;
namespace expr = boost::log::expressions;
BOOST_LOG_GLOBAL_LOGGER(MBLog, src::severity_logger_mt<logging::trivial::severity_level>)
Logger.cpp
#include "Logger.h"
#include <boost/log/support/date_time.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
void full_detail_formatter(logging::record_view const& rec, logging::formatting_ostream& strm);
void normal_formatter(logging::record_view const& rec, logging::formatting_ostream& strm);
BOOST_LOG_GLOBAL_LOGGER_INIT(MBLog, src::severity_logger_mt<logging::trivial::severity_level>)
{
src::severity_logger_mt<logging::trivial::severity_level> lg;
logging::add_common_attributes();
auto file_sink = logging::add_file_log(
keywords::file_name = "./logs/L%Y-%m-%d_%3N.log", // one file per date and execution
keywords::rotation_size = 5 * 1024 * 1024, // rotate after 5MB
keywords::target = "./logs",
keywords::min_free_space = 30 * 1024 * 1024,
keywords::auto_flush = true,
keywords::scan_method = boost::log::sinks::file::scan_matching
);
file_sink->set_formatter(&full_detail_formatter);
file_sink->set_filter(
logging::trivial::severity >= logging::trivial::trace
);
auto console_sink = logging::add_console_log(std::clog);
console_sink->set_formatter(&full_detail_formatter);
console_sink->set_filter(
logging::trivial::severity >= logging::trivial::trace
);
logging::core::get()->set_filter(
logging::trivial::severity >= logging::trivial::trace
);
return lg;
}
修改
似乎有人已经通过在执行asio::io_service::run
后为async_read_some
创建线程来解决此问题here
答案 0 :(得分:0)
似乎某人已经通过在执行async_read_some后为asio :: io_service :: run创建线程来解决此问题
是。否则,run()
可能会在任何工作注册之前完成。
其中的文档在这里:http://www.boost.org/doc/libs/1_65_0/doc/html/boost_asio/reference/io_service/run/overload1.html
run()函数会阻塞,直到所有工作完成,并且不再有调度程序,或者直到io_service停止。
可以找到更多解释:
请考虑使用io_service::work
:boost asio post not working , io_service::run exits right after post