Sunday, 15 January 2012

c++ - Possibility of segmentation fault with mutex in class with multithreading -



c++ - Possibility of segmentation fault with mutex in class with multithreading -

with multiple threads (std::async) sharing instance of next class through shared_ptr, possible segmentation fault in part of code? if understanding of std::mutex correct, mutex.lock() causes other threads trying phone call mutex.lock() block until mutex.unlock() called, access vector should happen purely sequentially. missing here? if not, there improve way of designing such class (maybe std::atomic_flag)?

#include <mutex> #include <vector> class foo { private: std::mutex mutex; std::vector<int> values; public: foo(); void add(const int); int get(); }; foo::foo() : mutex(), values() {} void foo::add(const int value) { mutex.lock(); values.push_back(value); mutex.unlock(); } int foo::get() { mutex.lock(); int value; if ( values.size() > 0 ) { value = values.back(); values.pop_back(); } else { value = 0; } mutex.unlock(); homecoming value; }

disclaimer: default value of 0 in get() intended has special meaning in rest of code.

update: above code utilize it, except typo push_back of course.

other not using raii acquire lock , using size() > 0 instead of !empty(), code looks fine. how mutex meant used , quintessential illustration of how , need mutex.

as andy prowl pointed out, instances can't re-create constructed or re-create assigned.

c++ c++11 thread-safety segmentation-fault mutex

No comments:

Post a Comment