std::thread::native_handle

native_handle_type native_handle();
(C++11 起)

返回实现定义的底层线程句柄。

目录

参数

(无)

返回值

表示线程的实现定义句柄类型。

异常

(无)

示例

在 POSIX 系统上用 native_handle 启用 C++ 线程的实时调度

#include <thread>
#include <mutex>
#include <iostream>
#include <chrono>
#include <cstring>
#include <pthread.h>
 
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::thread 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';
    }
 
    t1.join(); t2.join();
}

输出:

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

版本历史

  • (当前 | 先前 2017年8月25日 (五) 04:53Fruderica讨论 | 贡献. . (1,349字节) (-598). . (撤销)
  • 当前 | 先前 2012年11月2日 (五) 18:22P12bot讨论 | 贡献 . . (1,947字节) (+313). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:32P12讨论 | 贡献 . . (1,634字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,634字节) (+1,634). . (Translated from the English version using Google Translate)