C++ 11 스레딩 라이브러리를 사용하여 멀티 스레딩 (일반적으로 멀티 스레드)을 시작했으며 작은 코드를 작성했습니다.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;
}
두 스레드 간의 경쟁으로 인해이 프로그램을 실행할 때마다 (또는 매 시간마다) 다른 결과가 나올 것으로 예상됩니다. 그러나 출력은 항상 : 0
입니다. 즉 두 개의 스레드가 순차적으로 실행되는 것처럼 실행됩니다. 왜 내가 같은 결과를 얻고 두 스레드 사이에서 경쟁을 시뮬레이션하거나 강제 할 수있는 방법이 있습니까?
그래서 경쟁 조건은 항상 * 정의되지 않은 * 동작입니다. ;) –
CPU에는 몇 개의 코어가 있습니까? – DeathByTensors
코어 4 개, 코어 i3 – newprint