std::thread::native_handle(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

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