4 ms·
Isn't the very first example error prone? The one under Wait-freedom https://www.1024cores.net/home/lock-free-algorithms/introduction https://www.1024cores.net
by shultays 4y ago
Isn't the very first example error prone? The one under Wait-freedom
https://www.1024cores.net/home/lock-free-algorithms/introduction https://www.1024cores.net/home/lock-free-algorithms/introduc...
A thread can easily decrease the reference count to zero and delete the object while another thread is trying to add reference
- pkhuong 4y agoReference counting algorithms usually assume that code increments through a strong reference.
- gpderetta 4y agoFor another thread to be able to add a reference, it must already have a reference to that object, so the reference count can't be less than two. Two threads can't be both operating on the same pointer object. Reference counted pointers themselves are usually not atomic, only the reference count updates are. To atomically access the reference counted pointer itself, you need either a different algorithm (using hazard pointers for example), or some form of mutual exclusion.
- shultays 4y agoAha, makes sense. Thanks for the explanation
- pdpi 4y ago> Reference counted pointers themselves are usually not atomic, only the reference count updates are. Fun way to start an argument where everybody is wrong: ask a group of C++ programmers whether std::shared_ptr is thread-safe.
- TillE 4y agoshared_ptr's thread safety is simple: it's perfectly thread-safe as long as each thread has its own copy. It of course does not provide any synchronization for the object it's pointing to.
- kccqzy 4y agoAlmost exactly one month ago I have a junior developer share the same shared_ptr across threads, where some threads could be writing to it by calling reset(). They forget that accessing the shared_ptr itself needs to be protected. Rust prevents this problem completely though. You are either going to deal with Arc<Mutex<T>> or Mutex<Arc<T>>, depending on the situation (in this case the latter), and forgetting the Mutex will simply cause compilation failure.
- maxbond 4y agoRelated talk from cppcon: https://youtu.be/lkgszkPnV8g https://youtu.be/lkgszkPnV8g