System Thread Interface

  • std::thread uses the system's thread implementation
  • We may need to use the thread implementation directly
  • Some functionality is not available in standard C++:
    • Thread priority
      • Gives a thread higher or lower share of processor time
    • Thread affinity
      • "Pin" a thread on a specific processor core

native_handle()

  • Each execution thread has a "handle"

    • Used internally by the system's thread implementation
    • Needed when making calls into the implementation's API
  • Returned by the native_handle() member function

// Get the handle associated with an std::thread object
thr.native_handle()


#include <iostream>
#include <thread>

// Task function
void hello() { std::cout << "Hello, thread!" << std::endl; }

int main() {
  // create thread object
  std::thread thr(hello);

  // Display child thread's native handle
  std::cout << "Hello thread has native handle " << thr.native_handle() << '\n';

  // Wait for the thread to complete
  thr.join();

  std::cout << "Hello thread now has native handle " << thr.native_handle()
            << '\n';
}

std::thread ID

  • Each execution thread has a thread identifier

    • Used internally by the system's implementation
  • Guaranteed to be unique

    • If two thread identifiers are equal, the related objects are identical
    • Could be used to store std::thread objects in associative containers
    • A new thread may get the ID of an earlier thread which has completed

// Return the identifier of the current thread
std::this_thread::get_id();

// Return the identidier associated with an std::thread object
thr.get_id();


#include <iostream>
#include <thread>

// Task function
// Display thread ID
void hello() {
  std::cout << "Hello from thread with ID " << std::this_thread::get_id()
            << '\n';
}

int main() {
  // Display main thread ID
  std::cout << "Main thread has ID " << std::this_thread::get_id() << '\n';

  // create thread object
  std::thread thr(hello);

  // Display child thread's native handle
  std::cout << "Hello thread has ID " << thr.get_id() << '\n';

  // Wait for the thread to complete
  thr.join();

  std::cout << "Hello thread now has id " << thr.get_id() << '\n';
}

Pausing Threads

  • We can pause a thread or make it "sleep"
std::this_thread::sleep_for()
  • Takes an argument of type std::chrono::duration
// C++14
std::this_thread::sleep_for(2s);

// C++11
std::this_thread::sleep_for(std::chrono::seconds(2));
  • This also works with single-threaded programs
    • Pauses the thread which executes main()

#include <iostream>
#include <thread>

using namespace std::literals;

void hello() {
  std::this_thread::sleep_for(2s);
  std::cout << "hello, thread!\n";
}

int main() {
  std::cout << "Starting thread...\n";
  std::thread thr(hello);

  thr.join();
}