如何实现不会阻止其用户的引擎类
How to implement engine class which doesn't block its user
我有class,我们称之为"Engine",它包含类似事件循环的东西,其逻辑可以用以下伪代码来解释:
for(;;) {
int interruptId;
waitForInterrupt(); // blocking wait
switch(interruptId) {
case REQUEST_DATA:
doSomeStuff();
...
}
}
事件循环用于中断处理(来自硬件设备的驱动程序)。引擎将由客户端使用。客户端应该能够启动/停止引擎。但是启动引擎不应挂起客户端。
我的意图:当引擎启动时,它会启动一个新线程,其中执行 (;;) 的事件循环。
问题是这是一个解决方案,您能否提出适用于这种情况的现有设计模式,关于实现的任何建议以及我应该考虑的可能瓶颈。
铌!!!更新:引擎类作为动态库提供给客户端
#include <thread>
#include <functional>
#include <vector>
#include <iostream>
#include <memory>
#include <cassert>
struct MsgFromAgent {
std::string str;
};
struct MsgToAgent {
std::string str;
};
struct IClient {
virtual void onMsgFromBC(MsgFromAgent& msg) = 0;
virtual void onTimeout() = 0;
virtual ~IClient() {};
};
struct Engine {
Engine(IClient& client) : isRunning(false), client(client) { }
~Engine() {
// we expect that if client started the engine
// client must stop it before Engine will be destructed
assert(!isRunning && "Running engine should be stoped by the client");
// in any way, handle exceptional situation if it arises
if(isRunning) {
isRunning = false;
th.join();
}
}
void start() {
isRunning = true;
th = std::thread(std::bind(&Engine::eventLoop, this));
}
bool write(const MsgToAgent& msg) {
// some code
}
void stop() {
isRunning = false;
th.join();
}
void eventLoop() {
while(isRunning) {
// blocking calls, that return control when certain interrupts from hardware arrives
// if interrupt haven't arraived within certain time limit:
try {
client.onTimeout();
} catch(...) {
}
// interrupt about incomming msg:
MsgFromAgent dummyMsg;
try {
client.onMsgFromBC(dummyMsg);
}
catch (...) {
}
}
}
bool isRunning;
std::thread th;
IClient& client;
};
struct Client : public IClient {
Client() : e(*this) {
};
~Client() {
}
void onMsgFromBC(MsgFromAgent& msg) {
std::cout << "On messagen";
}
void onTimeout() {
std::cout << "On timeoutn";
}
Engine e;
};
int main() {
Client c;
return 0;
}
相关文章:
- C++如何通过用户输入删除列表元素
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- 当使用带有VS2019或VSCode的虚幻引擎4.24.2时,我如何修复这些错误的Intellisense错误
- 在C++中,我如何接受不同于同一行的用户输入
- 当用户超过按钮点击限制时报告
- Visual C++(VS2017)中用户定义的转换不明确
- Unity在虚幻引擎4中的"Vector3.Slerp"等效C++?
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 当用户键入分隔符时,停止getline()输入
- 如何实现不会阻止其用户的引擎类