std::shared_ptr<int> int_ptr;
int main() {
int_ptr = std::make_shared<int>(1);
std::thread th{[&]() {
std::weak_ptr int_ptr_weak = int_ptr;
auto int_ptr_local = int_ptr_weak.lock();
if (int_ptr_local) {
cout << "Value in the shared_ptr is " << *int_ptr_local << endl;
}
});
int_ptr.reset(nullptr);
th.join();
return 0;
}
위 코드는 스레드 안전합니까? 나는이 대답 About thread-safety of weak_ptr을 읽었지만, 위의 코드가 쓰레드에 안전한지 확인하고 싶었다.어떻게`weak_ptr` 및`shared_ptr` 액세스가 원자 단위입니까?
위의 코드가 실제로 스레드 안전 인 경우 std::weak_ptr
및 std::shared_ptr
인터페이스가 다음 작업을 원자 단위로 처리하는 방법을 이해할 수 없음 expired() ? shared_ptr<T>() : shared_ptr<T>(*this)
. 위와 같은 두 개의 논리적 인 코드 라인을 만드는 것은 일종의 뮤텍스 나 스핀 록을 사용하지 않고는 동기화할 수 없다는 것입니다.
원자 증분이 공유 포인터의 다른 인스턴스에서 작동하는 방식을 알고 있고 shared_ptr
자체가 스레드 안전하지 않다는 것을 이해합니다. 그러나 위의 스레드가 실제로 안전 할 경우 스레드 안전과 매우 비슷합니다. shared_ptr
과는 다릅니다. 위의 조건 에서처럼 두 줄의 코드를 자물쇠없이 원자 단위로 만들 수있는 방법을 이해합니다.
* "매우 안전한 스레드입니다. shared_ptr ''* - 공유 된''shared_ptr'을 사용하여''weak_ptr''을 쓰레드로부터 안전하게 만드십니까? – Holt
구현이 mutex를 사용하여 'lock'원자를 만드는 것을 멈추게하는 것은 아무것도 없습니다. 그러나 매우 효율적이지는 않을 것입니다. – Oktalist