[D-runtime] What's with core.sync.condition usage?
Steve Schveighoffer
schveiguy at yahoo.com
Thu Apr 26 07:50:40 PDT 2012
A condition variable is logically attached to an arbitrary condition as defined in your code (such as, there is an element in a queue). The proper sequence for using a condition is:
lock(mutex);
while(logicalConditionIsFalse) cond.wait();
// processCondition, e.g. remove element from queue
unlock(mutex);
It doesn't work like an event in Windows, and events in windows do *not* protect external conditions, the event *is* the condition.
For mutex/conditions, only threads waiting *at the time* you signal a condition will be woken up. So you have to have a mutex to protect the state of the condition, otherwise, you might miss the condition signal. You also avoid needless waiting/locking.
You might build mutex/conditions into a more high-level object (such as a queue), which would hide the details, but the primitives are correct, and time-tested.
Now, I'm all for a use case of storing the mutex in the condition and having the condition "own" the mutex, but that should not be a limitation, you should be able to attach multiple conditions to the same mutex, which means none of them own it.
-Steve
>________________________________
> From: Alex Rønne Petersen <xtzgzorex at gmail.com>
>To: D's runtime library developers list <d-runtime at puremagic.com>
>Sent: Wednesday, April 25, 2012 8:18 PM
>Subject: Re: [D-runtime] What's with core.sync.condition usage?
>
>Surely it could lock whatever it needs to lock internally?
>
>See: http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx
>
>That class is entirely thread safe.
>
>Regards,
>Alex
>
>On Thu, Apr 26, 2012 at 1:17 AM, Jonathan M Davis <jmdavisProg at gmx.com> wrote:
>> On Thursday, April 26, 2012 00:41:40 Alex Rønne Petersen wrote:
>>> Hi,
>>>
>>> What's with the weird, convoluted way one is supposed to use
>>> core.sync.condition.Condition? Having to lock on a mutex while using a
>>> Condition object is extremely weird compared to APIs in other
>>> programming languages. Any particular reason behind this design?
>>
>> Really? In C++, from what I've seen, you always end up locking on a mutex to
>> protect a condition variable. How could it work _without_ locking? The
>> condition variable wouldn't be protected against multiple threads using it.
>>
>> - Jonathan M Davis
>> _______________________________________________
>> D-runtime mailing list
>> D-runtime at puremagic.com
>> http://lists.puremagic.com/mailman/listinfo/d-runtime
>_______________________________________________
>D-runtime mailing list
>D-runtime at puremagic.com
>http://lists.puremagic.com/mailman/listinfo/d-runtime
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/d-runtime/attachments/20120426/3291e5cf/attachment.html>
More information about the D-runtime
mailing list