新增:实现 EventQueue 类,单线程事件队列

This commit is contained in:
2025-09-01 18:46:27 +08:00
commit 7b0d4fd2c3
9 changed files with 255 additions and 0 deletions

46
code/EventQueue.cpp Normal file
View File

@ -0,0 +1,46 @@
#include "EventQueue.h"
bool EventQueue::EventQueue_AddEvent(int tInputCmd, void *pInputParam)
{
cmdParam.push_back(pInputParam);
cmdList.push_back(tInputCmd);
return true;
}
bool EventQueue::EventQueue_AddEventToFront(int tInputCmd, void *pInputParam)
{
cmdParam.push_front(pInputParam);
cmdList.push_front(tInputCmd);
return true;
}
bool EventQueue::EventQueue_PeekEvent(int *pOutputCmd, void **ppOutputParam)
{
if (cmdList.empty())
return false;
(*pOutputCmd) = cmdList.front();
(*ppOutputParam) = cmdParam.front();
return true;
}
void EventQueue::EventQueue_PopEvent(void)
{
if (!cmdList.empty())
{
cmdList.pop_front();
cmdParam.pop_front();
}
}
bool EventQueue::EventQueue_GetEvent(int *pOutputCmd, void **ppOutputParam)
{
if (cmdList.empty())
return false;
(*pOutputCmd) = cmdList.front();
(*ppOutputParam) = cmdParam.front();
cmdList.pop_front();
cmdParam.pop_front();
return true;
}

23
code/EventQueue.h Normal file
View File

@ -0,0 +1,23 @@
#ifndef EVENTQUEUE_H
#define EVENTQUEUE_H
#include <pthread.h>
#include <unistd.h>
#include <iostream>
#include <list>
class EventQueue
{
public:
bool EventQueue_AddEvent(int tInputCmd, void *pInputParam);
bool EventQueue_AddEventToFront(int tInputCmd, void *pInputParam);
bool EventQueue_PeekEvent(int *pOutputCmd, void **ppOutputParam);
void EventQueue_PopEvent(void);
bool EventQueue_GetEvent(int *pOutputCmd, void **ppOutputParam);
private:
std::list<int> cmdList;
std::list<void *> cmdParam;
};
#endif

43
code/main.cpp Normal file
View File

@ -0,0 +1,43 @@
#include "EventQueue.h"
int main()
{
EventQueue queue;
/* 模拟事件数据 */
int cmd1 = 101;
std::string param1 = "事件一";
int cmd2 = 202;
std::string param2 = "事件二";
int cmd3 = 303;
std::string param3 = "事件三";
std::cout << "=== 添加事件 ===" << std::endl;
queue.EventQueue_AddEvent(cmd1, &param1); // 队尾
queue.EventQueue_AddEventToFront(cmd2, &param2); // 队头
queue.EventQueue_AddEvent(cmd3, &param3); // 队尾
/* 查看队头事件 */
int peekCmd;
void *peekParam;
if (queue.EventQueue_PeekEvent(&peekCmd, &peekParam))
{
std::cout << "[Peek] cmd=" << peekCmd
<< " param=" << *(std::string *)peekParam << std::endl;
}
std::cout << "=== 获取并移除事件 ===" << std::endl;
int getCmd;
void *getParam;
while (queue.EventQueue_GetEvent(&getCmd, &getParam))
{
std::cout << "[Get] cmd=" << getCmd
<< " param=" << *(std::string *)getParam << std::endl;
// queue.EventQueue_PopEvent(); // 队列中 Get 已经 pop 了PopEvent 可省略
}
std::cout << "=== 队列已清空 ===" << std::endl;
return 0;
}