Format Thread ID in C++23

Format Thread ID in C++23

Displaying thread identifiers is a common requirement in multithreaded programs. Thread IDs are useful for logging, debugging, and monitoring concurrent execution. Traditionally, printing a thread ID required converting it manually to a string, often using string streams or platform-specific functions, which could be verbose or inconsistent.

Since C++23, the std::format provides a simpler way to handle thread IDs. The std::thread::id can be inserted directly into formatted strings, producing clear and consistent output without the need for manual conversions.

The following example demonstrates how to obtain the current thread ID and format it for console output:

#include <iostream>
#include <format>
#include <thread>

int main() {
    std::thread::id id = std::this_thread::get_id();
    std::string str = std::format("Thread ID: {}", id);

    std::cout << str << std::endl;

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.