Multi-threaded Access
suggest changeAn atomic type can be used to safely read and write to a memory location shared between two threads.
A Bad example that is likely to cause a data race:
#include <thread>
#include <iostream>
//function will add all values including and between 'a' and 'b' to 'result'
void add(int a, int b, int * result) {
for (int i = a; i <= b; i++) {
*result += i;
}
}
int main() {
//a primitive data type has no thread safety
int shared = 0;
//create a thread that may run parallel to the 'main' thread
//the thread will run the function 'add' defined above with parameters a = 1, b = 100, result = &shared
//analogous to 'add(1,100, &shared);'
std::thread addingThread(add, 1, 100, &shared);
// joinable() is already true, and it stays true until join() or detach().
// A loop on !joinable() would not run. These reads can race with the worker.
for (int n = 0; n < 100; ++n) {
std::cout << shared << std::endl;
}
// join the thread at the end of execution for cleaning purposes
addingThread.join();
return 0;
}
The above example may cause a corrupted read and can lead to undefined behavior.
An example with thread safety:
#include <atomic>
#include <thread>
#include <iostream>
//function will add all values including and between 'a' and 'b' to 'result'
void add(int a, int b, std::atomic<int> * result) {
for (int i = a; i <= b; i++) {
//atomically add 'i' to result
result->fetch_add(i);
}
}
int main() {
//atomic template used to store non-atomic objects
std::atomic<int> shared{0};
//create a thread that may run parallel to the 'main' thread
//the thread will run the function 'add' defined above with parameters a = 1, b = 10000, result = &shared
//analogous to 'add(1,10000, &shared);'
std::thread addingThread(add, 1, 10000, &shared);
// Same joinable() rule as above. load() does not race with fetch_add.
for (int n = 0; n < 100; ++n) {
std::cout << shared.load() << std::endl;
}
// join the thread at the end of execution for cleaning purposes
addingThread.join();
return 0;
}
The atomic example is safe because fetch_add and load do not race with each other. Copy-initialization (std::atomic<int> shared = 0;) is ill-formed before C++17, because std::atomic is neither copyable nor movable, so the object is direct-initialized.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents