Lesson 38 of 45
C++Lesson 38: Threads (std::thread)
12 min
Course progress84%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 38 of 45
C++12 min
Keep these ideas in mind as you work through the lesson.
std::thread)C++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.
#include <thread>
void doWork(int id) {
std::cout << \"Thread \" << id << \" is working\
\";
std::this_thread::sleep_for(std::chrono::milliseconds(200));
std::cout << \"Thread \" << id << \" finished\
\";
}
int main() {
std::thread t1(doWork, 1);
std::thread t2([](int id) {
std::cout << \"Lambda thread \" << id << \" started\
\";
}, 2);
t1.join();
t2.join();
return 0;
}
std::cout << \"Hardware threads: \" << std::thread::hardware_concurrency() << '\
';
std::thread t([]{ std::cout << \"Current thread id: \" << std::this_thread::get_id() << '\
'; });
t.join();
Tip: Always
join()ordetach()a thread before itsstd::threadobject is destroyed; otherwise the program terminates.
<Alert type="warning">Accessing shared data from multiple threads without synchronization leads to data races.