mrn
mrn

Reputation: 1081

What is a potentially shared memory location?

In C11 and C++11 standard there appear a statement potentially shared memory location. What does this mean? Are all global variables potentially shared in a multithreaded environment?

Upvotes: 2

Views: 109

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

Not very familiar with the C standard. In C++14, the phrase "potentially shared memory location" appears twice, in two non-normative notes:

[intro.multithread]/25 [ Note: Compiler transformations that introduce assignments to a potentially shared memory location that would not be modified by the abstract machine are generally precluded by this standard, since such an assignment might overwrite another assignment by a different thread in cases in which an abstract machine execution would not have encountered a data race. This includes implementations of data member assignment that overwrite adjacent members in separate memory locations. Reordering of atomic loads in cases in which the atomics in question may alias is also generally precluded, since this may violate the coherence rules. — end note ]

[intro.multithread]/26 [ Note: Transformations that introduce a speculative read of a potentially shared memory location may not preserve the semantics of the C++ program as defined in this standard, since they potentially introduce a data race. However, they are typically valid in the context of an optimizing compiler that targets a specific machine with well-defined semantics for data races. They would be invalid for a hypothetical machine that is not tolerant of races or provides hardware race detection. — end note ]

From context, it's pretty clear that "potentially shared memory location" is supposed to mean "a memory location for which the optimizer cannot rule out the possibility that other threads may access it, and therefore should proceed on the pessimistic assumption that they might." The two notes then discuss the legality of certain optimizations that may or may not be done under such an assumption.

Re: global variables. Yes, a global variable would generally be accessible to arbitrary threads. It is conceivable, in principle, that a sophisticated optimizer performing whole program optimization might be able to prove that a particular global variable is never accessed concurrently from multiple threads (I'm not aware of any actual compilers currently in existence capable of achieving such a feat, but then I wouldn't call myself a compiler expert by any stretch). Barring that, memory locations occupied by a global variable should be treated by an optimizer as potentially shared.

Upvotes: 2

Related Questions