QStateMachine的同步问题
Synchronization issue with QStateMachine
我的程序中有一个QStateMachine
的实例。我在它的构造函数中配置它的状态、转换和初始状态。当然,我从构造函数开始。
this->stateA = new StateA(this);
this->stateB = new StateB(this);
this->stateA->addTransition(this, &Machine::foo, this->stateB);
this->setInitialState(this->stateA);
this->start();
// At this point the machine is still not in the stateA
我面临的问题是,在start()
完成执行之前,机器不会移动到初始状态。这导致了一个问题,即在进入初始状态之前发出信号foo
,该信号本应将机器从初始状态移动到另一个状态。
Machine* machine = new Machine();
// start() was already called here but the machine is still not in the initial state
machine->foo();
// Signal is emitted here (It also may not be emitted. This is not an unconditional transition). But the machine is still not in the initial state and the transition does not happen.
// ...
// Here the machine enters the initial state...
如何确保机器在建造时处于初始状态?
状态机是异步的,由事件循环驱动。您没有理由在启动时使用该信号将机器移动到另一种状态。目前,您希望在启动时从stateA
转换到stateB
,并且每当发出foo
时都要转换到。
-
请记住,连接的目标可以是信号,也可以是插槽。您可以将状态机的
started
信号连接到foo
信号。这样,当机器启动并处于初始状态时,foo
将被发射。 -
如果您不关心
foo
信号,您可以将转换设置为直接在机器的started
信号上触发。 -
如果总是希望从
stateA
转换到stateB
,即使在机器启动并以某种方式重新输入stateA
一段时间后,您也可以无条件地从初始状态转换到stateB
。机器在输入stateA
后将离开,然后自动输入stateB
。
从最后一个解决方案开始检查解决方案,如果您需要一个不太通用的解决方案,请向上移动。
您可以通过在构造函数中创建如下事件循环来确保机器在构建时处于初始状态:
// ...
this->start();
QEventLoop* eventLoop = new QEventLoop(this);
QObject::connect(
this, &Machine::started,
eventLoop, &QEventLoop::quit
);
eventLoop->exec();
相关文章:
- 线程过程中的线程同步问题
- 使用 qt 和 opengl、定时精度和垂直同步问题、c++ 显示图像
- C++11 中 3 个线程和 2 个共享资源的同步问题
- 队列的同步问题
- C++ 获取同步密钥状态状态问题
- Google 日历与订阅日历"Remember the milk"同步问题
- Qt QState机器同步问题:初始状态未在启动信号上设置
- POSIX线程同步和/或pthread_create()参数传递问题
- 线程同步问题
- MP3帧头检测FFF/FFE同步问题
- 线程同步问题
- 在同步问题中,弱指针可以代替互斥锁或临界区吗?
- 与MPI-2单向通信同步单个int值的问题
- 同步MPI-2单向通信中的顺序问题
- QStateMachine的同步问题
- c++并发、同步设计,避免多次执行问题
- 录制视频和音频-同步问题
- Poco 线程同步问题
- Boost Asio:关于教程的一些问题(同步日间服务器/客户端)
- Turbo c++文件同步问题