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

Reply via email to