Search⌘ K

Multithreading: Threads

Explore the fundamental concepts of threads in modern C++ concurrency. Understand why using tasks is often preferable to raw threads, learn how to safely communicate between threads, avoid race conditions, and implement joinable threads using wrappers to maintain thread safety.

Threads

Threads are the basic building blocks for writing concurrent programs.

Use tasks instead of threads

C++
// asyncVersusThread.cpp
#include <future>
#include <thread>
#include <iostream>
int main(){
std::cout << std::endl;
int res;
std::thread t([&]{ res = 2000 + 11; });
t.join();
std::cout << "res: " << res << std::endl;
auto fut= std::async([]{ return 2000 + 11; });
std::cout << "fut.get(): " << fut.get() << std::endl;
std::cout << std::endl;
}

Based on the program, there are a lot of reasons for preferring tasks over threads. These are the main reasons:

  • you can use a safe communication channel for returning the result of the communication. If you use a shared
...