Skip to content

Threads_basics

C++11 introduced native threading support. This chapter covers how to create and manage threads in C++.

#include <thread>
#include <iostream>
void hello() {
std::cout << "Hello from thread!\n";
}
int main() {
std::thread t(hello); // Create thread running hello()
t.join(); // Wait for thread to complete
std::cout << "Main thread continues\n";
return 0;
}
#include <thread>
#include <iostream>
void print(int x, const std::string& msg) {
std::cout << msg << ": " << x << "\n";
}
int main() {
// Arguments are copied by default
std::thread t1(print, 42, "Answer");
// Use std::ref for references
int value = 100;
std::thread t2(print, value, "Value"); // Copies value
t1.join();
t2.join();
return 0;
}
#include <thread>
void worker() {}
int main() {
std::thread t(worker);
// Join - wait for thread to finish
t.join();
// Detach - let thread run independently
std::thread t2(worker);
t2.detach(); // Now runs in background
// Check if joinable
if (t.joinable()) { t.join(); }
return 0;
}
int main() {
int counter = 0;
std::thread t([&counter]() {
for (int i = 0; i < 1000; i++) {
counter++;
}
});
t.join();
std::cout << "Counter: " << counter << "\n";
return 0;
}
#include <thread>
#include <iostream>
int main() {
std::thread t([]() {});
std::cout << "Main thread ID: " << std::this_thread::get_id() << "\n";
std::cout << "Worker thread ID: " << t.get_id() << "\n";
t.join();
return 0;
}
  • Use std::thread to create concurrent execution
  • Always join() or detach() threads before destruction
  • Use lambdas with captures for complex thread functions
  • Thread arguments are copied by default

Let’s learn about mutexes for thread synchronization.

Next Chapter: 36_mutex_locks.md - Mutexes and Locking