What is the point of a synchronized lock on a single return statement?

Steven Schveighoffer schveiguy at gmail.com
Mon Nov 25 15:40:58 UTC 2019


On 11/25/19 3:22 AM, Andrej Mitrovic wrote:
> From: 
> https://github.com/dlang/phobos/blob/10b9174ddcadac52f6a1ea532deab3310d3a8c03/std/concurrency.d#L1913-L1916: 
> 
> 
> -----
> ///
> final @property bool isClosed() @safe @nogc pure
> {
>      synchronized (m_lock)
>      {
>          return m_closed;
>      }
> }
> -----
> 
> I don't understand the purpose of this lock. The lock will be released 
> as soon as the function returns, and it returns a copy of a boolean 
> anyway. Am I missing something here?

Locks ensure the CPU and compiler use the correct memory model. It's 
complicated, but necessary. Look up Herb Sutter's atomic weapons talk. 
The key takeaway is that the "gurus" who make compilers and cpus have 
the rule "If you use mutex locks, the code will behave like you wrote it 
for all observations". With out the locks, crazy things can happen.

Note also, that even though x86 CPUs are atomic for single values 
without locks, not all CPUs are. However, I think a bool is likely 
always atomic. But that doesn't mean the compiler or CPU will not 
reorder your instructions. The locks keep it consistent.

-Steve


More information about the Digitalmars-d-learn mailing list