1) shared_ptr의 레퍼런스 카운팅은 thread safe하다
2) 즉 shared_ptr의 control block(레퍼런스 카운트 정보를 담고 있는 부분, 참고)은 thread safe 하다
3) 그러나, shared_ptr 자체가 가리키는 객체는 thread safe하지 않다
4) C++20부터는 atomic_shared_ptr의 사용이 가능하다
// Thread-safe
std::shared_ptr<int> ptr = std::make_shared<int>(4);
for (auto i =0;i<10;i++){
std::thread([ptr]{ auto copy = ptr; }).detach(); //ok, only mutates the control block
}
// 스레드별 값이 달라지게 된다
// NOT SAFE
std::shared_ptr<int> ptr = std::make_shared<int>(4);
std::thread threadA([&ptr]{
ptr = std::make_shared<int>(10);
});
std::thread threadB([&ptr]{
ptr = std::make_shared<int>(20);
});
https://stackoverflow.com/questions/40223599/what-is-the-difference-between-stdshared-ptr-and-stdexperimentalatomic-sha
프로젝트 제작 중 이것저것 찾아보다 배우게 된 내용이다.
정말 흥미롭게도 내가 필요로 하는 기능은 control block의 thread-safety만 보장되면 되는 경우라 굳이 atomic_shared_ptr까지 사용하지 않아도 되었다
'lang > c++' 카테고리의 다른 글
가상 소멸자 (0) | 2023.08.30 |
---|---|
템플릿 사용 시 LNK1120 "확인할 수 없는 외부 참조" 발생 (0) | 2023.08.24 |
atan, atan2 (0) | 2022.07.05 |
std::iterator, std::advance (0) | 2022.05.18 |
Bitwise operator (C/C++) (0) | 2021.08.20 |