命名空间
变体
操作

thrd_sleep

来自 cppreference.cn
< c‎ | thread
在头文件 <threads.h> 中定义
int thrd_sleep( const struct timespec* duration,
                struct timespec* remaining );
(C11 起)

阻塞当前线程的执行,直到 duration 指向的基于 TIME_UTC 的持续时间至少过去。

如果收到未被忽略的 信号,睡眠可能会提前恢复。在这种情况下,如果 remaining 不为 NULL,则剩余持续时间存储在 remaining 指向的对象中。

目录

[编辑] 参数

duration - 指向睡眠持续时间的指针
remaining - 指向对象以在中断时放置剩余时间的指针。可以为 NULL,在这种情况下被忽略

[编辑] 返回值

成功睡眠时为 0,如果发生信号则为 -1,如果发生错误则为其他负值。

[编辑] 注意

durationremaining 可以指向同一个对象,这简化了信号后重新运行函数。

实际睡眠时间可能比请求的时间长,因为它向上舍入到定时器粒度,并且由于调度和上下文切换开销。

此函数的 POSIX 等效项是 nanosleep

[编辑] 示例

#include <threads.h>
#include <time.h>
#include <stdio.h>
 
int main(void)
{
    printf("Time: %s", ctime(&(time_t){time(NULL)}));
    thrd_sleep(&(struct timespec){.tv_sec=1}, NULL); // sleep 1 sec
    printf("Time: %s", ctime(&(time_t){time(NULL)}));
}

输出

Time: Mon Feb  2 16:18:41 2015
Time: Mon Feb  2 16:18:42 2015

[编辑] 参考

  • C17 标准 (ISO/IEC 9899:2018)
  • 7.26.5.7 thrd_sleep 函数 (p: 281)
  • C11 标准 (ISO/IEC 9899:2011)
  • 7.26.5.7 thrd_sleep 函数 (p: 385)

[编辑] 另请参阅

让出当前时间片
(函数) [编辑]
C++ 文档用于 sleep_for