我正在熟悉boost線程和信號。因此,我正在實現這個簡單的例子,我只發佈一個示例類的cpp文件,該類實現了一個Signal1被觸發時能夠執行方法的線程。該信號是Package1Signals單中定義的(請原諒我這些名字,他們已經從模型生成的)boost:線程不會在接收到信號後發送處理程序
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";
}
Package1.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
Package1.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;
}
我可以看到線程運行的代碼,該信號被截取,但不執行發佈處理。我究竟做錯了什麼?
您的構造函數會阻塞,直到線程退出,因此永遠不會到達發送信號的下一行。 – 2012-07-10 17:54:40