Fully thread-safe shared_ptr implementation

后端 未结 9 1478
面向向阳花
面向向阳花 2021-02-02 17:02

Does anybody know of a fully thread-safe shared_ptr implementation? E.g. boost implementation of shared_ptr is thread-safe for the targets (refcounting

9条回答
  •  佛祖请我去吃肉
    2021-02-02 17:20

    Simultaneous write to a built-in pointer is certainly not thread safe. Consider the implications of writing to the same value with respect to memory barriers if you really want to drive yourself crazy (for instance, you could have two threads thinking the same pointer had different values).

    RE: Comment - the reason built-ins aren't double deleting is because they aren't deleting at all (and the implementation of boost::shared_ptr I use wouldn't double delete, since it uses a special atomic increment and decrement, so it would only single delete, but then the result would could have the pointer from one and the ref count of the other. Or pretty much any combination of the two. It would be bad.). The statement in the boost docs is correct as it is, you get the same guarantees as you do with a built-in.

    RE: EDIT2 - The first situation you are describing are very different between using built-ins and shared_ptrs. In one (XCHG and manual delete) there's no reference count; you are assuming you are the one and only owner when you do this. If using shared pointers, you are saying other threads might have ownership, which makes things far more complex. I believe it is possible with a compare-and-swap, but this would be very non-portable.

    C++0x is coming out with an atomics library, which should make it much easier to write generic multi-threaded code. You'll probably have to wait till that comes out to see good cross-platform reference implementations of thread-safe smart pointers.

提交回复
热议问题