gpt4 book ai didi

C 设计模式在不阻塞的情况下执行操作列表?

转载 作者:行者123 更新时间:2023-12-04 10:37:05 26 4
gpt4 key购买 nike

嵌入式 C。我有一个我想做的事情列表,程序上,主要是 READ 和 WRITE 和 MODIFY 操作,根据最后一条语句的结果进行操作。他们每个最多可能需要 2 秒,我无法阻止。

每个 Action 都可以有 COMPLETE 和 ERROR 状态,它们具有发生错误的原因的子状态。或者在比赛中我想检查或修改一些数据。

每个 Action 列表都是一个很大的开关,为了重新进入,我会保留一个我正在执行的步骤的列表,一个成功的步骤++,下次我会回到列表的更下方。

很简单,但我发现为了不阻塞,我需要花费大量精力不断检查状态、错误和边缘。一遍又一遍。

我会说我的 80% 的代码只是检查和移动系统。一定有更好的方法!

是否有任何异步操作的设计模式,然后以有效处理某些异常/边缘/处理的方式返回结果?

编辑:我知道如何使用回调,但并没有真正将其视为“解决方案”,因为我只需要返回同一列表的不同部分以进行下一步操作。也许了解其他语言中 async 和 await 如何工作的后端会有所帮助?

Edit2:我确实有一个用于其他项目的 RTOS,但是这个特定的问题,假设没有线程/任务,只是裸机 super 循环。

最佳答案

您的困境非常适合状态机(实际上,可能是 UML statecharts )。每个不同的请求都可以在自己的状态机中处理,状态机以非阻塞、运行到完成的方式处理事件(例如 COMPLETE ERROR 指示)。随着事件的到来,请求的状态机会通过其不同的状态向完成移动。

对于嵌入式系统,我经常使用 QP event-driven framework对于此类情况。事实上,当我查找此链接时,我注意到第一段使用了“非阻塞”一词。该框架提供的不仅仅是具有层次结构(状态中的状态)的状态机,它已经非常强大。

该站点还提供了一些有关解决您的特定问题的方法的好信息。我建议从网站的 Key Concepts 开始页。

为了让您了解内容及其与您的困境的相关性:

In spite of the fundamental event-driven nature, most embedded systems are traditionally programmed in a sequential manner, where a program hard-codes the expected sequence of events by waiting for the specific events in various places in the execution path. This explicit waiting for events is implemented either by busy-polling or blocking on a time-delay, etc.

The sequential paradigm works well for sequential problems, where the expected sequence of events can be hard-coded in the sequential code. Trouble is that most real-life systems are not sequential, meaning that the system must handle many equally valid event sequences. The fundamental problem is that while a sequential program is waiting for one kind of event (e.g., timeout event after a time delay) it is not doing anything else and is not responsive to other events (e.g., a button press).

For this and other reasons, experts in concurrent programming have learned to be very careful with various blocking mechanisms of an RTOS, because they often lead to programs that are unresponsive, difficult to reason about, and unsafe. Instead, experts recommend [...] event-driven programming.



你也可以自己做状态机而不使用像 QP 这样的事件驱动框架,但你最终会重新发明轮子 IMO。

关于C 设计模式在不阻塞的情况下执行操作列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60123606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com