QT里QElapsedTimer使用,实现伪并行
一、首先定义好变量
MsDeviceState_e cState_m;
QElapsedTimer timer_m;
QList<MsDeviceState_e> lstDeviceState;
MsDeviceState_e cState_m 是个枚举,对应各个状态
enum MsDeviceState_e{
DEVICE_IDLE = 0,
DEVICE_WORK_START,
DEVICE_WORK_1,
.....
.....
DEVICE_FINISH
};
定义一个QList lstDeviceState 来存放各个状态
二、状态机
代码如下(示例):
void Mainwindows::MachineRun()
{
switch(cState_m){
case DEVICE_IDLE:
{
}break;
case DEVICE_WORK_START:
{
MoveNextState(cState_m);
timer_m.restart();
}break;
case DEVICE_WORK_1:
{
//这里可以延迟
int delay = 3000;
if(timer_m.hasExpired(delay)){
//这里进行要做的事务
MoveNextState(cState_m);
timer_m.restart();
}
}break;
......
}
bool MainWindows::MoveNextState(MsDeviceState_e& dst)
{
if(lstDeviceState.size()<=0){
dst = DEVICE_IDLE;
return false;
}
dst = lstDeviceState.front();
lstDeviceState.pop_front();
timer_m.restart();
return true;
}
当然最后调用MachineRun()是在主线程里面,while(1)里或者在个定时器里一直刷
if(lstDeviceState.size() == 0){
lstDeviceState.clear();
lstDeviceState.push_back(DEVICE_WORK_1);//
......
cState_m = DEVICE_WORK_START;
}
//调用machinerun
machinerun();
这样大致就能实现并行了