我正在用幾個有限狀態機在qt/Linux中構建一個嵌入式系統。每個FSM都有自己的事件隊列和一個連續運行的線程函數。 FSM可能會向彼此發佈事件。EventQueues和互斥體
顯然事件隊列在訪問時應該被鎖定和解鎖。 我應該將互斥鎖放入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():
}
謝謝!
'bool isEmpty(){mutex.lock();返回false; mutex.unlock(); }和你的互斥鎖永遠不會解鎖!返回後無法訪問。 – Evgeny
您應該改用QMutexLocker。 – Evgeny
好趕上哈哈。確實使用mutexlocker來避免這些booboos – Teimpz