c++ - C ++异步从其他函数获取数据
问题描述
这不是编码,而是主要是架构问题......
例如,我有一个loop()
函数,我从某个源(在我的例子中是 UART)获取数据。代码很像这样(伪代码):
loop() {
auto data = UART.GetData();
// differ data from each other and push it to corresponding message queue or golang-style channel?
Console.Print(data);
}
我需要实现一个异步 REST HTTP 函数,它将从 UART 预订(订购)数据并等待它到来。请记住,此时其他异步 REST HTTP 函数也可能会从 UART 请求数据。异步 REST HTTP 函数的代码如下:
handler(AsyncRequest &req) {
UART.RequestNeededData(); // This function returns nothing. Data will be handled in loop() method
auto data = // somehow get this data from other method, in this case it's loop() (get data from message queue or Golang-style channel?)
req.SendDataToClient(data);
}
UART 运行它自己的协议来区分请求的数据和响应。把它当作 req/res 数据包。我需要将请求的数据从handler()
函数传递回handler()
.
希望您了解我需要做什么,并可以帮助我解决这个问题。如果您有任何问题,请发表评论。
解决方案
我用队列模板类解决了类似的问题:
QueuePendingCommands<char> queue(100); //-> Max 100 chars in this queue
处理程序初始化适当的队列并用数据填充它
auto data = UART.GetData();
if (data = fullfillConditionA )
if (data != '\n')
QueuePendingCommandsA.push(data);
else
processResponse(QueuePendingCommandsA);
else if (data = fullfillConditionB )
if (data != '\n')
QueuePendingCommandsB.push(data);
else
processResponse(QueuePendingCommandsB);
else ....
在我的情况下,有一个定义的最终字符(例如'#'或'\n'),将其推入队列会触发清空队列并填充响应:
void processResponse (inQueue) {
/** Create response - Drain the queued up commands */
while (inQueue.count() > 0) {
strcat(response, inQueue.pop());
}
.... Do something with the response
}
因此,对于每个请求,您都会写入一个已定义的队列,并在收到特殊字符后触发响应(也是固定数量的字符,条件或超时可能会触发队列的清空)
推荐阅读
- php - 如何使用 Microsoft 提供的 (PDO_SQLSRV) 代码登录以访问 AdventureWorks Production 表?
- c# - Hangfire - 在站点运行时部署不会重新加载应用程序 c# asp.net mvc
- angular - 订阅后角度不刷新组件
- daml - DAML:对单独模板中的预定义列表进行引用和设置条件
- javascript - 函数中的 Firestore 查询每次返回不同的快照
- css - 我该怎么做
在 Angular 9 中显示消息时不会展开 - java - 如果我在 Spring JPA Gradle 项目的 Jar 文件中找不到 jks 文件怎么办?
- google-apps-script - GMail Google Apps 脚本插件“从 Apps 脚本返回的值的类型不能被插件平台使用”
- python - 从文件夹中读取文件并将其附加到 xlsx 文件
- javascript - 如何使用 Selenium 和 Python 从 Javascript 中获取变量值