名稱空間
變體
操作

thrd_yield

來自 cppreference.com
< c‎ | thread
在標頭檔案 <threads.h> 中定義
void thrd_yield(void);
(C11 起)

向實現提供一個提示,以重新排程執行緒的執行,允許其他執行緒執行。

目錄

[編輯] 引數

(無)

[編輯] 返回值

(無)

[編輯] 注意

此函式的具體行為取決於實現,特別是所使用的作業系統排程器的機制和系統狀態。例如,先進先出即時排程器(Linux 中的 SCHED_FIFO)會暫停當前執行緒並將其放在相同優先順序就緒執行執行緒佇列的末尾,如果不存在其他相同優先順序的執行緒,則 yield 沒有效果。

此函式的 POSIX 等價物是 sched_yield

[編輯] 示例

#include <stdio.h>
#include <time.h>
#include <threads.h>
 
// utility function: difference between timespecs in microseconds
double usdiff(struct timespec s, struct timespec e)
{
    double sdiff = difftime(e.tv_sec, s.tv_sec);
    long nsdiff = e.tv_nsec - s.tv_nsec;
    if(nsdiff < 0) return 1000000*(sdiff-1) + (1000000000L+nsdiff)/1000.0;
    else return 1000000*(sdiff) + nsdiff/1000.0;
}
 
// busy wait while yielding
void sleep_100us()
{
    struct timespec start, end;
    timespec_get(&start, TIME_UTC);
    do {
        thrd_yield();
        timespec_get(&end, TIME_UTC);
    } while(usdiff(start, end) < 100.0);
}
 
int main()
{
    struct timespec start, end;
    timespec_get(&start, TIME_UTC);
    sleep_100us();
    timespec_get(&end, TIME_UTC);
    printf("Waited for %.3f us\n", usdiff(start, end));
}

可能的輸出

Waited for 100.344 us

[編輯] 參考

  • C17 標準 (ISO/IEC 9899:2018)
  • 7.26.5.8 thrd_yield 函式 (p: 281)
  • C11 標準 (ISO/IEC 9899:2011)
  • 7.26.5.8 thrd_yield 函式 (p: 385)

[編輯] 另請參閱

暫停呼叫執行緒的執行指定時間
(函式) [編輯]
C++ 文件 for yield