std::atomic
연산이 완전히 수행되거나 아예 수행되지 않는 상태를 보장해주며
멀티쓰레딩 환경에서 데이터 경쟁 조건을 방지해준다.
멀티 쓰레드 환경에서의 연산 결과
int cnt = 0;
void Add()
{
for (int i = 0; i < 1000000; ++i)
{
cnt += 1;
}
}
int main()
{
std::thread t1(Add);
std::thread t2(Add);
t1.join();
t2.join();
cout << cnt << endl;
}
연산 결과가 원하는 대로 나오지 않는 이유
atomic을 사용하여 연산이 완전히 수행되거나 아예 수행되지 않는 상태를 보장
// InterlockedAdd() 에서
// c++11에서 도입된 방법 데이터 경쟁 조건 방지
// ㄴ 공유데이터 관리 => 하지만 병목으로 연산이 느림
#include <atomic>
std::atomic<int> cnt = 0;
void Add()
{
for (int i = 0; i < 100'0000; ++i)
{
cnt += 1;
}
}
int main()
{
std::thread t1(Add);
std::thread t2(Add);
t1.join();
t2.join();
cout << cnt << endl;
}
'C, C++' 카테고리의 다른 글
[[deprecated]] (0) | 2025.01.26 |
---|---|
<mutex> (0) | 2024.02.22 |
<thread> (0) | 2024.02.20 |
weak_ptr (0) | 2023.07.17 |
shared_ptr (0) | 2023.07.16 |