Lesson 32 of 45 · C++
Lesson 38: Threads (std::thread)
Duration: 12 min
Lesson 32 of 45 · C++
Duration: 12 min
std::thread)\n\nC++11 introduced native threading support via the <thread> library. A std::thread represents a single thread of execution. You can start a thread with any callable object: a function pointer, lambda, functor, or member function.\n\n---\n\n## Example: Launching a thread with a lambda\ncpp\n#include <thread>\n\nvoid doWork(int id) {\n std::cout << \"Thread \" << id << \" is working\\n\";\n std::this_thread::sleep_for(std::chrono::milliseconds(200));\n std::cout << \"Thread \" << id << \" finished\\n\";\n}\n\nint main() {\n std::thread t1(doWork, 1);\n std::thread t2([](int id) {\n std::cout << \"Lambda thread \" << id << \" started\\n\";\n }, 2);\n t1.join();\n t2.join();\n return 0;\n}\n\n\n## Thread IDs and hardware concurrency\ncpp\nstd::cout << \"Hardware threads: \" << std::thread::hardware_concurrency() << '\\n';\nstd::thread t([]{ std::cout << \"Current thread id: \" << std::this_thread::get_id() << '\\n'; });\n t.join();\n\n\n> Tip: Always join() or detach() a thread before its std::thread object is destroyed; otherwise the program terminates.\n\n---\n\n<Alert type="warning">Accessing shared data from multiple threads without synchronization leads to data races.