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

Andrea Fontana nospam at example.com
Mon Nov 25 09:52:02 UTC 2019


On Monday, 25 November 2019 at 09:24:43 UTC, Jonathan M Davis 
wrote:
> On Monday, November 25, 2019 1:22:17 AM MST Andrej Mitrovic via 
> Digitalmars- d-learn wrote:
>> From: 
>> https://github.com/dlang/phobos/blob/10b9174ddcadac52f6a1ea532deab3310d3a8 c03/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?
>
> It ensures that no other code that locks m_lock is running when 
> m_closed is accessed. I'd have to study std.concurrency in 
> detail to know for sure why that would be needed, but it's not 
> atypical when trying to maintain consistent state when multiple 
> threads are interacting with each other.
>
> - Jonathan M Davis


Probably to be sure to have a consistent status returned. See for 
example:

https://github.com/dlang/phobos/blob/10b9174ddcadac52f6a1ea532deab3310d3a8c03/std/concurrency.d#L2250




More information about the Digitalmars-d-learn mailing list