Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I just want to confirm it's safe to reset to the same smart pointer with lock in multi-threads? if there is no lock_guard, it's not safe due to it is not a thread-safe method? I suppose reset is not threadsafe, however, no crash is observed if I removed the lock.
class foo {
public:
foo()
std::cout << "foo constructed" << std::endl;
~foo()
std::cout << "foo destructed" << std::endl;
int main(int argc, const char * argv[]) {
std::shared_ptr<foo> f = std::make_shared<foo>();
conqueue = dispatch_queue_create("MyConcurrentDiapatchQueue", DISPATCH_QUEUE_CONCURRENT);
static std::mutex io_mutex;
for (int i = 0; i < 100000; i++)
dispatch_async(conqueue, ^{
std::lock_guard<std::mutex> lk(io_mutex); // no crash without this line as well
f.reset(); // it's safe? No crash if I reset the same shared_ptr in multi-threads.
return 0;
–
–
The shared_ptr
object is not thread-safe, nor is the pointed-to object. Only the reference count is thread-safe. So yes, you need to use a guard.
In C++20, there is std::atomic<std::shared_ptr<T>>
.
–
Documentation don't guarantee safety of that component. Essentially if standard says nothing about it then your assumption is right. You have to have that lockquard or anything that provides same functionality.
Crash might be no observable because you don't have racing condition until you try read pointer in a concurrent thread because you don't actually try to use that value (all that reset does is to change pointer value).
Well and you can't rely on that you can't observe an UB, UB is a Schrodinger's cat.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.