My code does some processing, and it writes intermediate results into an array, which I can later write to file. I want to break it into threads, but their processing regions will overlap, so some intermediate results will be written twice. Both threads will write the same value to the same array element.
Example:
#include <iostream>
#include <thread>
int array[4];
void f1()
{
array[0] = 10;
array[1] = 11;
}
void f2()
{
array[1] = 11;
array[2] = 12;
}
void f3()
{
array[2] = 12;
array[3] = 13;
}
int main()
{
std::thread t1(f1);
std::thread t2(f2);
std::thread t3(f3);
t1.join();
t2.join();
t3.join();
for (int x: array)
std::cout << x << '\n';
}
This code outputs the expected result (10 11 12 13
). But is this guaranteed, or does it have undefined behavior? Do I need to protect some array elements with mutexes or anything else, so they are only ever written once?