#C 语言标准库函数 thrd_sleep
/*********************************************
* @brief 阻塞当前线程一段时间
* @param duration 阻塞时长
* @param[out] remaining 中断时返回剩余时间
* @return 是(非 0)否(0)相同
********************************************/
int thrd_sleep(const struct timespec* duration, struct timespec* remaining);
说明
阻塞当前线程一段时间(基于 TIME_UTC
)。
如果收到未被忽略的 信号,可能会提前解除阻塞;此时通过 remaining
参数返回剩余时间。
结构体类型
struct timespec
可能的定义(字段顺序未定义)如下:
struct timespec { time_t tv_sec; // 秒,有效值范围 >= 0 long tv_nsec; // 纳秒,有效值范围为 [0, 999999999] }
或
struct timespec { long tv_nsec; // 纳秒,有效值范围为 [0, 999999999] time_t tv_sec; // 秒,有效值范围 >= 0 }
在 C23 之前
tv_nsec
的类型为long
;在 C23 之后,tv_nsec
的类型由实现定义。
参数
duration
- 阻塞时长remaining
- 中断时返回剩余时间,可以为NULL
即不接收该返回
返回值
- 成功时返回 0
- 中断时返回 -1
- 其它错误返回 -1 以外的负值
#示例
#include <stdio.h>
#include <threads.h>
#include <time.h>
int main(void)
{
// 阻塞时间
struct timespec duration = {
.tv_sec = 5,
};
// 剩余时间
struct timespec remaining;
printf("开始时间: %s", ctime(&(time_t){time(NULL)}));
// 睡眠
while (thrd_sleep(&duration, &remaining) == -1)
{
duration = remaining; // 中断时继续睡眠剩余时间
}
printf("结束时间: %s", ctime(&(time_t){time(NULL)}));
return 0;
}
运行结果:
开始时间: Fri Aug 22 14:36:02 2025 结束时间: Fri Aug 22 14:36:07 2025
#推荐阅读
#参考标准
- C17 standard (ISO/IEC 9899:2018):
- 7.26.5.7 The thrd_sleep function (p: 281)
- C11 standard (ISO/IEC 9899:2011):
- 7.26.5.7 The thrd_sleep function (p: 385)