如何实现不会阻止其用户的引擎类

How to implement engine class which doesn't block its user

本文关键字:用户 引擎 何实现 实现      更新时间:2023-10-16

我有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;
}