我正在qt/Linux中用几台有限状态机构建一个嵌入式系统。每个FSM都有自己的事件队列和一个持续运行的线程函数。FSM可以互相发布事件。
显然,在访问时,事件队列应该被锁定和解锁。我应该在FSM,EventQueue中放置互斥,还是让它成为传递给FSM的全局变量?
下面是伪代码:
class EventQueue {
int queue[100];
int head;
int tail;
void postEvent(int event) {
// place the event to circular buffer
// checking of head/tail neglected
queue[tail++] = event;
}
int getNextEvent() {
// checking of head/tail neglected
return queue[head++];
}
bool isEmpty() {
return false; // or true if the queue is not empty
}
};
class FSM {
EventQueue queue;
FSM * other;
pthread_t thread;
void start() {
int t = pthread_create( &thread, NULL, FSM::run, NULL);
}
// thread function
void * run(void *) {
while (true) {
if (!queue.isEmpty()) {
int e = queue.getNextEvent();
dispatch(e); // should be perform by state class actually
}
}
}
virtual void dispatch(int event) = 0;
};
class FSM_A : FSM {
void dispatch(int event) {
other->postEvent(1234); // send event to other state machine
usleep(100);
}
};
class FSM_B : FSM {
void dispatch(int event) {
other->postEvent(4567); // send event to other state machine
usleep(200);
}
};
void main() {
FSM_A fsmA;
FSM_B fsmB;
fsmA.other = &fsmB;
fsmB.other = &fsmA;
fsmA.start():
fsmB.start():
}谢谢!
发布于 2016-01-11 16:12:06
我认为最简单的解决方案是用互斥锁锁你的队列。
class EventQueue {
int queue[100];
int head;
int tail;
Mutex mutex; // std::mutex or QMutex or whatever you prefer.
void postEvent(int event) {
MutexLocker( mutex ); // f.e. QMutextLocker or std::lock_guard
// place the event to circular buffer
// checking of head/tail neglected
queue[tail++] = event;
}
int getNextEvent() {
MutexLocker( mutex );
// checking of head/tail neglected
return queue[head++];
}
bool isEmpty() {
// No lock is needed if no variables are read.
return false; // or true if the queue is not empty
}
};如果一个变量是从多个线程读取/写入的,那么在读/写过程中锁定每条读或写指令是很重要的。
访问每个命令队列时,不需要锁定其中一个命令队列。我会在EventQueue中放置互斥锁
编辑:正如注释中指出的,使用MutexLocker锁定互斥锁是安全得多的。通过这种方式,您可以确定在函数作用域结束时它将被释放。
发布于 2016-01-11 16:31:05
在实体设计methodology..If中遵循单责任原则,类FSM使用eventQueue,EventQueue内部管理事件队列,而EventQueue则负责处理自己的内部队列,usage.The FSM不必为EventQueue的内部结构而烦恼。
https://stackoverflow.com/questions/34725710
复制相似问题