Threads_basics
Thread Basics
Section titled “Thread Basics”C++11 introduced native threading support. This chapter covers how to create and manage threads in C++.
Creating Threads
Section titled “Creating Threads”#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;}Passing Arguments to Threads
Section titled “Passing Arguments to Threads”#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;}Thread Management
Section titled “Thread Management”#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;}Lambda Threads
Section titled “Lambda Threads”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;}Thread ID
Section titled “Thread ID”#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;}Key Takeaways
Section titled “Key Takeaways”- Use
std::threadto create concurrent execution - Always
join()ordetach()threads before destruction - Use lambdas with captures for complex thread functions
- Thread arguments are copied by default
Next Steps
Section titled “Next Steps”Let’s learn about mutexes for thread synchronization.
Next Chapter: 36_mutex_locks.md - Mutexes and Locking