std::thread
Creating and managing threads
Interview Relevant: Multithreading basics
std::thread
Create and manage threads for parallel execution.
Code Examples
Basic thread creation and management.
cpp
1#include <thread>
2
3// Basic thread creation
4void task() {
5 cout << "Running in thread" << endl;
6}
7thread t(task);
8t.join(); // Wait for completion
9
10// Thread with arguments
11void greet(const string& name) {
12 cout << "Hello, " << name << endl;
13}
14thread t2(greet, "Alice");
15t2.join();
16
17// Lambda thread
18thread t3([]() {
19 cout << "Lambda thread" << endl;
20});
21t3.join();
22
23// Detach thread (runs independently)
24thread t4(task);
25t4.detach(); // Can't join anymore
26
27// Check if joinable
28if (t.joinable()) {
29 t.join();
30}
31
32// Get thread ID
33cout << this_thread::get_id() << endl;
34
35// Number of hardware threads
36unsigned int n = thread::hardware_concurrency();
37
38// Pass by reference (use ref wrapper)
39void modify(int& x) { x++; }
40int val = 0;
41thread t5(modify, ref(val));
42t5.join();