我开始熟悉 boost 线程和信号。因此,我正在实现这个简单的示例,我只发布了一个示例类的 cpp 文件,该类实现了一个能够在触发 Signal1 时执行方法的线程。该信号是在 Package1Signals 单例中定义的(请原谅这些名称,它们是从模型生成的)
Class1.hpp
#ifndef CLASS1_HEADER
#define CLASS1_HEADER
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/udp.hpp>
#include <boost/asio/signal_set.hpp>
#include "Package1.hpp"
#include <boost/thread.hpp>
class Class1{
private:
boost::asio::io_service service;
public:
boost::thread thread;
Class1();
void classifierBehavior();
void Reception1(Signal1 signal1);
void Reception1Behavior();
};
#endif
Class1.cpp
#include "Class1.hpp"
#include <boost/thread.hpp>
#include <boost/date_time.hpp>
#include "Package1.hpp"
#include "Package2.hpp"
#include "Package1.hpp"
Class1::Class1(){
//boost::thread thread(boost::bind(&Class1::classifierBehavior,boost::ref(*this)));
//thread.join();
thread = boost::thread(&Class1::classifierBehavior,this);
};
void Class1::classifierBehavior(){
Package1Signals::getInstance()->signal1.connect(boost::bind(&Class1::Reception1,
this,_1));
service.run();
};
void Class1::Reception1(Signal1 signal1){
std::cout<<"Signal received\n";
service.post(boost::bind(&Class1::Reception1Behavior, this));
}
void Class1::Reception1Behavior(){
std::cout<<"Behavior executed\n";
}
包1.hpp
#ifndef PACKAGE1_HEADER
#define PACKAGE1_HEADER
#include <boost/signal.hpp>
struct Signal1{ };
class Package1Signals{
private:
Package1Signals();
static Package1Signals * instance;
public:
boost::signal<void(Signal1)> signal1;
static Package1Signals * getInstance();
};
#endif
包1.cpp
#include "Package1.hpp"
Package1Signals * Package1Signals::instance = NULL;
Package1Signals::Package1Signals(){}
Package1Signals * Package1Signals::getInstance(){
if(!instance){
instance = new Package1Signals();
}
return instance;
}
这是执行它的代码
int main() {
Class1 test;
Package1Signals::getInstance()->signal1();
test.thread.join();
int k =0;
std::cin>>k;
return 0;
}
我可以看到线程运行,信号被拦截但未执行发布的处理程序。我究竟做错了什么?