I was having the understanding that when two threads simultaneously read and write from/to the same variable, the application would crash. I wrote a small program to simulate this scenario. I ran it several times but do not notice any crash. What am I missing here?
#include <iostream>
#include <thread>
using namespace std;
int g_TestVar = 0;
void ReadFunction()
{
for (size_t i = 0; i < 5000; ++i) {
cout << this_thread::get_id() << "------" << g_TestVar << '\n';
}
}
void WriteFunction()
{
for (size_t i = 0; i < 5000; ++i) {
g_TestVar = rand();
}
}
int main()
{
thread ReadThread[100];
thread WriteThread[100];
for (size_t i = 0; i < 100; ++i) {
ReadThread[i] = thread(ReadFunction);
WriteThread[i] = thread(WriteFunction);
}
for (size_t i = 0; i < 100; ++i) {
ReadThread[i].join();
WriteThread[i].join();
}
return 0;
}