名稱空間
變體
操作

std::jthread::native_handle

來自 cppreference.com
< cpp‎ | thread‎ | jthread
 
 
併發支援庫
執行緒
(C++11)
(C++20)
this_thread 名稱空間
(C++11)
(C++11)
(C++11)
協同取消
互斥
(C++11)
通用鎖管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
條件變數
(C++11)
訊號量
門閂和屏障
(C++20)
(C++20)
期值
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
危險指標
原子型別
(C++11)
(C++20)
原子型別的初始化
(C++11)(C++20 中已棄用)
(C++11)(C++20 中已棄用)
記憶體排序
(C++11)(C++26 中已棄用)
原子操作的自由函式
原子標誌的自由函式
 
 
native_handle_type native_handle();
(C++20 起)
(不總是存在)

返回實現定義的底層執行緒控制代碼。

目錄

[編輯] 引數

(無)

[編輯] 返回值

表示執行緒的實現定義的控制代碼型別。

[編輯] 異常

可能丟擲實現定義的異常。

[編輯] 示例

使用 native_handle 在 POSIX 系統上啟用 C++ 執行緒的即時排程。

#include <chrono>
#include <cstring>
#include <iostream>
#include <mutex>
#include <pthread.h>
#include <thread>
 
std::mutex iomutex;
void f(int num)
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
 
    sched_param sch;
    int policy; 
    pthread_getschedparam(pthread_self(), &policy, &sch);
    std::lock_guard<std::mutex> lk(iomutex);
    std::cout << "Thread " << num << " is executing at priority "
              << sch.sched_priority << '\n';
}
 
int main()
{
    std::jthread t1(f, 1), t2(f, 2);
 
    sched_param sch;
    int policy; 
    pthread_getschedparam(t1.native_handle(), &policy, &sch);
    sch.sched_priority = 20;
    if (pthread_setschedparam(t1.native_handle(), SCHED_FIFO, &sch))
        std::cout << "Failed to setschedparam: " << std::strerror(errno) << '\n';
 
 
}

輸出

Thread 2 is executing at priority 0
Thread 1 is executing at priority 20