C++11 スレッド化ライブラリを使用してマルチスレッド化 (および一般的なマルチスレッド化) を始めたばかりで、短い短いコードを書きました。
#include <iostream>
#include <thread>
int x = 5; //variable to be effected by race
//This function will be called from a thread
void call_from_thread1() {
for (int i = 0; i < 5; i++) {
x++;
std::cout << "In Thread 1 :" << x << std::endl;
}
}
int main() {
//Launch a thread
std::thread t1(call_from_thread1);
for (int j = 0; j < 5; j++) {
x--;
std::cout << "In Thread 0 :" << x << std::endl;
}
//Join the thread with the main thread
t1.join();
std::cout << x << std::endl;
return 0;
}
2 つのスレッド間の競合のため、このプログラムを実行するたびに (またはほぼ毎回) 異なる結果が得られると予想していました。ただし、出力は常に : です0
。つまり、2 つのスレッドが順番に実行されたかのように実行されます。同じ結果が得られるのはなぜですか? 2 つのスレッド間の競合をシミュレートまたは強制する方法はありますか?