You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于单CPU的定时异步多任务C++实现的算法名称问询

单线程异步多任务实现的正式名称

我一直希望实现基础的异步多任务代码(非并发代码),要求不使用中断、boost库、复杂线程及复杂多任务实现或算法。我曾在ATmega328等MCU上编程,多数情况下为最大化MCU效能,需要实现多任务——让函数“看似”同时运行,且不会因某个函数延迟而暂停MCU,使其他函数可异步执行。

针对单CPU/线程的微控制器,可通过计时器与时间追踪算法实现此类多任务,该方法简单可靠。我将此MCU上的概念移植到桌面PC的C++中,使用高精度计时器实现了代码。

我惊讶于该类异步算法在C中几乎无应用案例,此前在网络上也未找到类似实现。我曾了解到这种实现被称为“状态机”,但搜索后未找到直接使用计时器的相似C代码。

以下代码可同时运行function_1与function_2,无需暂停应用,且两个函数按指定间隔执行(function_1每1秒运行一次,function_2每3秒运行一次),网络上同类需求的实现通常较为复杂,而此代码简洁且符合预期:

// Asynchronous state machine using one CPU C++ example:
// Tested working multitasking code:

#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>

using namespace std::chrono;

// At the first execution of the program, capture the time as zero reference and store it to "t2".
auto t2 = high_resolution_clock::now();
auto t3 = high_resolution_clock::now();

int main() 
{
  while (1)
  {
    // Always update the time reference variable "t1" to the current time:
    auto t1 = high_resolution_clock::now();

    // Always check the difference of the zero reference time with the current time and see if it is greater than the set time specified in the "if" argument:
    duration<double> time_span_1 = duration_cast<duration<double>>(t1 - t2);
    duration<double> time_span_2 = duration_cast<duration<double>>(t1 - t3);
      
    if(time_span_1.count() >= 1)
    {
      printf("This is function_1:\n\n");
      std::cout << time_span_1.count() << " Secs (t1-t2)\n\n";
      
      // Set t2 to capture the current time again as zero reference.
      t2 = high_resolution_clock::now();
      
      std::cout << "------------------------------------------\n\n";
    }

    else if (time_span_2.count() >= 3)
    {
      printf("This is function_2:\n\n");
      std::cout << time_span_2.count() << " Secs (t1-t3)\n\n";
      
      // Set t3 to capture the current time again as zero reference.
      t3 = high_resolution_clock::now();

      std::cout << "------------------------------------------\n\n";
    }
  }
  return 0;      
}

问题

该算法及实现在计算机科学或工程领域的正式名称是什么?

解答

你的实现属于非抢占式协作多任务(Non-Preemptive Cooperative Multitasking)的轻量变体,核心是轮询式时间触发任务调度(Polling-Based Time-Triggered Task Scheduling):

  • 非抢占式协作多任务:所有任务在同一个线程/CPU核心中执行,没有外部中断或线程调度器强制切换任务,完全依赖主循环轮询检查任务触发条件,任务执行完成后主动回到主循环,让其他任务有机会执行,这也是嵌入式MCU中最常用的轻量多任务模式之一。
  • 轮询式时间触发调度:每个任务的执行由预设的时间间隔触发,主循环持续检查当前时间与任务上次执行时间的差值,当满足间隔要求时执行任务,属于时间触发系统(Time-Triggered System)的极简实现。

你提到的“状态机”是这类实现的常见扩展方向——如果任务需要维护执行状态(比如分步完成复杂操作),通常会把任务拆分为状态机的不同阶段,在每次轮询时根据当前状态执行对应步骤,但你的代码中任务是无状态的单次执行,核心仍是轮询式时间触发的协作多任务。

内容的提问来源于stack exchange,提问作者Max Dax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:06:44