Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, you must understand that no operation is thread safe, but rather all operations on a given resource can be mutually thread safe. So we must discuss the behavior of non-assignment operator code.</p> <p>The simplest solution would be to make the data immutable, write an Aref class that uses the pImpl class to store an immutable reference counted A, and have mutating methods on Aref cause a new A to be created. You can achieve granularity by having immutable reference counted components of A (like B and C) follow a similar pattern. Basically, Aref becomes a COW (copy on write) pImpl wrapper for an A (you can include optimizations to handle single-reference cases to do away with the redundant copy).</p> <p>A second route would be to create a monolithic lock (mutex or reader-writer) on A and all of its data. In that case, you either need mutex ordering on the locks for instances of A (or a similar technique) to create a race-free operator=, or accept the possibly surprising race condition possibility and do the copy-swap idiom Dietmar mentioned. (Copy-move is also acceptable) (Explicit race condition in the lock-copyconstruct, lock-swap assignment operator=: Thread1 does X=Y. Thread 2 does Y.flag = true, X.flag = true. State afterwards: X.flag is false. Even if Thread2 locks both X and Y over the entire assignment, this can happen. This would surprise many programmers.)</p> <p>In the first case, non-assignment code has to obey the copy-on-write semantics. In the second case, non-assignment code has to obey the monolithic lock.</p> <p>As for exception safety, if you presume your copy constructor is exception safe, as is your lock code, the lock-copy-lock-swap one (the second) is exception safe. For the first one, so long as your reference counting, lock clone and data modification code is exception safe you are good: the operator= code is pretty brain dead in either case. (Make sure your locks are RAII, store all allocated memory in a std RAII pointer holder (with the ability to release if you end up handing it off), etc.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload