Following on from #95, let’s consider reasons and methods to avoid mutable sharing in the first place…



Problem



Consider the following code from GotW #95’s solution, where some_obj is a shared variable visible to multiple threads which then synchronize access to it.

// thread 1

{

lock_guard hold(mut_some_obj); // acquire lock

code_that_reads_from( some_obj ); // passes some_obj by const &

}



// thread 2

{

lock_guard hold(mut_some_obj); // acquire lock

code_that_modifies( some_obj ); // passes some_obj by non-const &

}

JG Questions



1. Why do mutable shared variables like some_obj make your code:

(a) more complex?

(b) more brittle?

(c) less scalable?

Guru Questions



2. Give an example of how the code that uses a mutable shared variable like some_obj can be changed so that the variable is:

(a) not shared.

(b) not mutable.

3. Let’s say we’re in a situation where we can’t apply the techniques from the answers to #2, so that the variable itself must remain shared and apparently mutable. Is there any way that the internal implementation of the variable can make the variable be physically not shared and/or not mutable, so that the calling code can treat it as a logically shared-and-mutable object yet not need to perform external synchronization? If so, explain. If not, why not?