我正在尝试将提升信号与asio混合以执行基于调度的处理程序调用。当从一个线程调用post方法时,io_service :: run立即退出,处理post的回调从不被调用,callback是一个C ++ 11 lambda例程。我正在粘贴代码以进行更多分析。
#include<iostream>
#include<thread>
#include<boost/signals2/signal.hpp>
#include<boost/asio.hpp>
static boost::asio::io_service svc;
static boost::signals2::signal<void(std::string)> textEntered;
static void
handleInputText(std::string text)
{
std::cout<<"handleInputText()"<<" text provided: "<<text;
return;
}
static void
worker()
{
sleep(2);
svc.post([](){
std::cout<<"\nRaising signal.";
std::string hello("hello world");
textEntered(hello);
});
return;
}
int main(int ac, char **av)
{
try
{
textEntered.connect(&handleInputText);
std::thread w(std::bind(&worker));
svc.run();
w.join();
}
catch(std::exception &ex)
{
std::cerr<<"main() exited with exception:"<<ex.what();
}
return 0;
}
答案 0 :(得分:2)
您实际上并未将任何工作发布到服务中。
你开始一个可能最终发布工作的主题,但主线程已经退出了。
要么在线程上运行ioservice,要么确保它有io_service::work
以下是使用专用服务主题和work
项目的修复程序:
<强> Live On Coliru 强>
#include<boost/asio.hpp>
#include<iostream>
#include<boost/asio.hpp>
#include<boost/signals2.hpp>
#include<boost/thread.hpp>
#include<boost/make_shared.hpp>
static boost::asio::io_service svc;
static boost::shared_ptr<boost::asio::io_service::work> work_lock;
static boost::signals2::signal<void(std::string)> textEntered;
static void
handleInputText(std::string text)
{
std::cout<<"handleInputText()"<<" text provided: "<<text;
return;
}
static void
worker()
{
sleep(2);
svc.post([](){
std::cout<<"\nRaising signal.";
std::string hello("hello world");
textEntered(hello);
});
return;
}
int main()
{
try
{
work_lock = boost::make_shared<boost::asio::io_service::work>(svc);
textEntered.connect(&handleInputText);
boost::thread_group tg;
tg.create_thread(boost::bind(&boost::asio::io_service::run, &svc));
tg.create_thread(&worker);
boost::this_thread::sleep_for(boost::chrono::seconds(3));
work_lock.reset();
tg.join_all();
}
catch(std::exception &ex)
{
std::cerr<<"main() exited with exception:"<<ex.what();
}
return 0;
}
打印:
Raising signal.handleInputText() text provided: hello world