Skip to content

在主循环里处理超时、计数回绕与有限重试 ​

每次主循环向状态机交当前时间和已匹配的应答,再根据返回的动作发请求或报告结果。每轮最多等待 20 ms,总共最多发 3 次。

沿执行路径读代码 ​

  1. 第一次调用发出请求,记录本轮起点。主循环可以在两次调用之间做别的工作。
  2. 用 uint32_t 的 now - started_at 算经过时间。严格小于 20 ms 才属于应答窗口,恰好 20 ms 按到期处理。
  3. 超时且剩余次数可用时,把重发动作交给调用方。所有次数用完后仅上报一次,直到调用者创建新的命令。

完整源码 ​

下载示例 main.c

c
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

enum { REPLY_TIMEOUT_MS = 20, MAX_ATTEMPTS = 3 };

typedef enum { READY, WAIT_REPLY, SUCCEEDED, FAILED } State;
typedef enum { NOTHING, SEND_REQUEST, REPORT_OK, REPORT_TIMEOUT } Action;
typedef struct
{
  State state;
  uint32_t started_at;
  unsigned attempts;
} Command;

// 每轮传入当前毫秒计数和本命令匹配的应答。SEND_REQUEST 交给调用者立刻发出。
// 两次调用间隔须小于计数完整回绕周期,且应答要由上层按本命令归属筛选。
static Action command_step(Command *command, uint32_t now, bool reply)
{
  // 1. 已经报告结果的命令保持终态,由调用者另建命令开始下一轮。
  if (command->state == SUCCEEDED || command->state == FAILED)
  {
    return NOTHING;
  }

  // 2. 等待期间先判断是否到期。窗口内收到应答就交给调用者报告成功。
  if (command->state == WAIT_REPLY &&
      (uint32_t)(now - command->started_at) < REPLY_TIMEOUT_MS)
  {
    if (reply)
    {
      command->state = SUCCEEDED;
      return REPORT_OK;
    }
    return NOTHING;
  }

  // 3. 首次调用或本次到期时才发起发送。次数用尽就报告超时,不再重发。
  if (command->attempts == MAX_ATTEMPTS)
  {
    command->state = FAILED;
    return REPORT_TIMEOUT;
  }
  ++command->attempts;
  command->started_at = now;
  command->state = WAIT_REPLY;
  return SEND_REQUEST;
}

int main(void)
{
  // 1. 计数在第一次发送后回绕,下一次轮询仍按无符号差计算经过时间。
  Command command = {.state = READY};
  assert(command_step(&command, UINT32_MAX - 9U, false) == SEND_REQUEST);
  assert(command_step(&command, 9U, false) == NOTHING);
  assert(command_step(&command, 10U, true) == SEND_REQUEST);
  assert(command_step(&command, 11U, true) == REPORT_OK);
  assert(command.attempts == 2U);
  assert(command_step(&command, 12U, true) == NOTHING);

  // 2. 另一条命令始终收不到应答。到达上限后只上报一次,后续轮询返回无动作。
  Command silent = {.state = READY};
  assert(command_step(&silent, 0U, false) == SEND_REQUEST);
  assert(command_step(&silent, 20U, false) == SEND_REQUEST);
  assert(command_step(&silent, 40U, false) == SEND_REQUEST);
  assert(command_step(&silent, 60U, false) == REPORT_TIMEOUT);
  assert(command_step(&silent, 61U, true) == NOTHING);
  puts("timed retry: wrap, reply, 3 attempts, single timeout");
  return 0;
}

编译和观察 ​

在仓库根目录用 PowerShell 运行。Linux 下去掉输出文件的 .exe 后缀,并用 ./.work/timed-retry 启动。

powershell
New-Item -ItemType Directory -Force .work | Out-Null
gcc -std=c11 -Wall -Wextra -Werror -pedantic examples/c/timed-retry/main.c -o .work/timed-retry.exe
& ./.work/timed-retry.exe

程序输出 timed retry: wrap, reply, 3 attempts, single timeout。计数从 UINT32_MAX - 9 开始,回绕后的 9 距起点 19 ms,10 距起点 20 ms。

练习 ​

预测题 为什么 now 变小后不会继续等到下次计数回到原值?

核对预测

时间差按无符号计数的模数计算。本例只关心短时间窗口,并要求轮询间隔小于完整回绕周期。

改动题 把最大发送次数改成 2,更新完全无应答的用例。

核对改法

保留 0 ms 和 20 ms 两次发送。40 ms 就报告超时,之后继续调用只得到 NOTHING。

验证记录 ​

已在 Windows 使用 GCC 15.2.0 编译并运行自测。