std::thread::native_handle(3)
Okay bestie, welcome to the std::thread::native_handle(3) page from the C++ Standard Libary manual β yep, manual name folded in right here, and yep, that spelling is exactly what the header says π. This is the little function that gives you the implementation defined underlying thread handle, and weβre gonna cover the signature, the zero parameters, the return situation, the maybe-exceptions, and a whole POSIX realtime-scheduling example. Slay.
π NAME π
std::thread::native_handle - std::thread::native_handle
Yes, itβs the same thing twice. Iconic. Periodt.
π¦ Synopsis π¦
The signature is here, and itβs giving tiny but mighty:
native_handle_type native_handle(); (since C++11)
(not always present)
Returns the implementation defined underlying thread handle.
Heads up, bestie: the synopsis literally says (not always present), so donβt assume this handle is always around, okay? π
πΈ Parameters πΈ
(none) β literally zero parameters. Not a single argument. Nada. The vibe check is empty in the best way.
β¨ Return value β¨
Implementation defined handle type representing the thread.
Thatβs the whole return-value moment, no cap.
π Exceptions π
May throw implementation-defined exceptions.
So like, keep that in mind. Itβs not out here promising zero drama π.
π Example π
Uses native_handle to enable realtime scheduling of C++ threads on a POSIX system.
// Run this code β thatβs the siteβs little run note, not C++ you need to live by.
#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::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();
}
π Output π
Thread 2 is executing at priority 0
Thread 1 is executing at priority 20
Cute sign-off time: this page comes from http://cppreference.com, dated 2024.06.10, and it is the std::thread::native_handle(3) page β byeee, go be the main character of your own thread π
β¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms