c++ - how to avoid non-deterministic read caused by concurrent write -
non-deterministic read caused concurrent write can demonstrated following code:
class bar { int val_; std::mutex m_; public: explicit bar(int v) : val_(v) {} int val() { std::lock_guard<std::mutex> l(m_); return val_; } void set(int v) { std::lock_guard<std::mutex> l(m_); val_ = v; } }; class foo { bar* bar_; public: explicit foo(bar* bar) : bar_(bar) {} int val() const { return bar_.val(); } }; bar bar(1); foo foo(&bar); cout << foo.val() << endl; // 1 bar.set(2); // executed in thread cout << foo.val() << endl; // 2
i interested know design patterns / coding practices avoid such problem.
one solution can think of make "deep copy", i.e. foo have consistent snapshot of data depends on, reads same result. if foo owns bar, can make bar ref counted, , let foo maintain list of different versions of bar (all mutation bar go through foo), , client "snapshot view" of foo have access 1 version of bar, i.e. consistent view. however, if foo not own bar, becomes mess , cannot think of solution here.
my opinion either data owner needs provide versioned access, or there must policy enforcing no write should happen before reader releases data.
if don't want value change, don't use mutable object.
if must use bar object, making copy have reference best way go this.
Comments
Post a Comment