-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
레이스 컨디션 재질문
20.08.21 22:47 작성 조회수 133
0
#include<iostream>
#include<thread>
#include<atomic>
#include<mutex>
#include<chrono>
using namespace std;
int main()
{
mutex mtx;
int shared_momory(0);
auto count_func = [&]() {
for (int i = 0; i < 1000; i++)
{
//this_thread::sleep_for(chrono::milliseconds(1));
//std::scoped_lock lock(mtx);
shared_momory++;
}
};
thread t1 = thread(count_func);
thread t2 = thread(count_func);
t1.join();
t2.join();
cout << "After" << endl;
cout << shared_momory << endl;
return 0;
}
코드는 이렇습니다.
답변을 작성해보세요.
1
1
Hello Yeo
2020.08.22
일단 코드상에서 this_thread:sleep_for(chrono::milliseconds(1)); 이 있건 없건 사실 race condition에 의한 상황이 일어날 수 있는 코드입니다. milliseconds(1) 를 넣어줘서 두 threads 가 서로 shared_memory에 접근하는 시간이 겹쳐질 수 있도록 의도한 코드인데... 여러 번 실행해도 항상 동일한 결과가 나타나나요? 배열의 크기를 늘려서 시도해보시는 것도 확인의 한 방법이 될 것 같습니다.
0
움직이는YM
질문자2020.08.21
저 같은 경우는
// this_thread::sleep_for(chrono::milliseconds(1));
이 쉬는 문장을 넣으면 정상적으로 나오고(atomic이나 기타 lock을 설정하지 않고도요)
// this_thread::sleep_for(chrono::milliseconds(1)); 이 문장을 빼면 레이스 컨디션이 발생합니다.
보여주신 것과는 반대인데요. 혹시 왜 그런지 알 수 있을까요? CPU 차이인가요?
제 컴퓨터의 CPU는 AMD인데 교수님의 CPU는 인텔인 것에 차이가 있는건가요? 라는 것이 질문 내용이었습니다
답변 3