名稱空間
變體
操作

thrd_sleep

來自 cppreference.com
< 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