【发布时间】:2017-03-22 01:38:54
【问题描述】:
我正在尝试使用std::thread 在使用 Boost MSM 库编码的状态机中实现并行行为。我正在使用std::thread 从状态A 的on_entry 方法启动一个线程,我想知道如何调用process_event 方法以便从该线程中触发一个事件。这是一个最小的工作示例:
#include <iostream>
#include <thread>
#include <unistd.h>
#include <boost/msm/back/state_machine.hpp>
#include <boost/msm/front/state_machine_def.hpp>
#include <boost/msm/front/functor_row.hpp>
namespace msm = boost::msm;
namespace msmf = boost::msm::front;
namespace mpl = boost::mpl;
// Events
struct timeout {};
struct outer_:msmf::state_machine_def<outer_> {
struct inner_:msmf::state_machine_def<inner_> {
template <class Event, class Fsm>
void on_entry(Event const&, Fsm&) {
std::cout << "[state machine entry] inner" << std::endl;
}
struct A:msmf::state<> {
template <class Event, class Fsm>
void on_entry(Event const&, Fsm& f) {
std::cout << "[state entry] A" << std::endl;
stop_threads_ = false;
thread_ = new std::thread(&A::func,this);
}
template <class Event, class Fsm>
void on_exit(Event const&, Fsm&) {
stop_threads_ = true;
thread_->join(); // wait for threads to finish
delete thread_;
std::cout << "[state exit] A" << std::endl;
}
void func() {
while (!stop_threads_) {
usleep(1000000);
std::cout << "Hello" << std::endl;
// QUESTION: how to call process_event(timeout()) here?
}
}
public:
std::thread* thread_;
bool stop_threads_;
};
struct Action {
template <class Event, class Fsm, class SourceState, class TargetState>
void operator()(Event const&, Fsm&, SourceState&, TargetState&) {
std::cout << "Trying again..." << std::endl;
}
};
typedef A initial_state;
struct transition_table:mpl::vector<
msmf::Row <A,timeout,A,Action>
> {};
};
typedef msm::back::state_machine<inner_> inner;
typedef inner initial_state;
};
typedef msm::back::state_machine<outer_> outer;
void waiting_thread() {
while(true) {
usleep(2000000);
}
}
int main() {
outer sm;
sm.start();
std::thread wait(waiting_thread);
wait.join();
}
我的问题是评论// QUESTION...,我想要一种方法来执行process_event 方法。感谢您的帮助!
【问题讨论】:
-
如前所述,此时您不能直接执行此操作。我所看到的是使用线程安全队列并在那里推送事件对象,然后使用线程在状态机中以序列化和线程安全的顺序处理_events。
标签: c++ multithreading boost