Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

shared_ptr 析构 fetch_sub 用 memroy_order_relaxed 会不会有问题? #18

Open
ravenxrz opened this issue Dec 10, 2024 · 0 comments

Comments

@ravenxrz
Copy link

ravenxrz commented Dec 10, 2024

https://github.com/parallel101/stl1weekend/blob/9c394fd48e1d69cb7686a420fc9e57161ad0acb6/SharedPtr.hpp#L18C1-L20C6

标准库里面释放管理的指针和控制块直接使用了 acq_rel fence的,这里直接用relaxed order不会有问题吗?
标准库实现如下:
image

考虑如下case, thread 1为最终减到1的thread, thread 2为减到2的 thread。thread 1最终释放资源。


void thread1(shared_ptr<T> ptr) {
    
    // ...
    
    if (ptr.counter.fetch_sub(1, relaxed) == 1)  // Will be true
        delete ptr.storage;
}
void thread2(shared_ptr<T> ptr) {

    // ...
    
    other_storage = *ptr;
    
    if (ptr.counter.fetch_sub(1, relaxed) == 1) // Will be false
        delete ptr.storage;
}

如果使用relaxed order,thread 2可重排为:

void thread2(shared_ptr<T> ptr) {

    // ...
    
    bool should_delete = ptr.counter.fetch_sub(1, relaxed) == 1

    other_storage = *ptr;  // 如果thread 1在这之前释放了storage,就有问题了。
    
    if (should_delete) 
        delete ptr.storage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant