Multithreading: Shared Data

This lesson gives an overall guide for best practices used to manage shared data in multithreaded applications in C++.

Data Sharing

With data sharing, the challenges in multithreading programming start.

Pass data per default by copy

Press + to interact
#include <iostream>
#include <thread>
#include <string>
int main(){
std::string s{"C++11"};
std::thread t1([s]{std::cout << s << std::endl; }); // do something with s
t1.join();
std::thread t2([&s]{ std::cout << s << std::endl; }); // do something with s
t2.join();
// do something with s
s.replace(s.begin(), s.end(), 'C', 'Z');
}

If you pass data such as the std::string s to a thread t1 by copy, the creator thread and the created thread t1 will use independent data; this is in contrast to the thread t2. It gets its std::string s by reference. This means you have to synchronize the access to s in the creator thread and the created thread t2 preventively. This is error-prone and expensive.

...