What sync object should i use?

Dmitry Olshansky dmitry.olsh at gmail.com
Tue May 14 12:02:52 PDT 2013


14-May-2013 21:02, Steven Schveighoffer пишет:
> On Tue, 14 May 2013 04:58:27 -0400, Dmitry Olshansky
> <dmitry.olsh at gmail.com> wrote:
>
>> 14-May-2013 08:33, Heinz пишет:
>>>> BTW, given recent discussion on memory barriers, I think my previous
>>>> statement that the mutex does not need to be locked to call notify is
>>>> probably incorrect.
>>>
>>
>> Have to lock it otherwise you have a race condition on a condition
>> variable (wow!).
>
> No, the issue would be reordering (is that possible in this case?).  The
> actual signaling of the condition would not require the lock, but you
> still need to lock to send the message (e.g. set the boolean) or you
> will definitely have issues.

Never had to notify without sending some message (otherwise how you'd 
affect the thread on the other side of fence?). I'd have to dig into how 
D's condition variables are done to say for sure. But I thought that 
notify is not re-entrant that is it needs to be locked (as there is a 
queue of threads to manage).

I just had fresh experience in Java where you basically can't notify 
threads waiting on the monitor without grabbing the lock, same with call 
to wait. It's a clean-cut run-time error (when it can detect it).

>
> But since you have to lock anyway, signaling while holding the lock, or
> while being outside the lock isn't really a difference.
>

On the level of gut feeling there must be something about it as you 
don't see:

synchronized(m){
	// ... send message
}
notify();

anytime of day. And hosting work out of mutex seems natural isn't it?
Not in condition to analyze just yet but one clue is that it seems like 
you may be notifying a thread that would wake up only to block on mutex 
somebody else holds.

> Maybe I'm wrong...

Maybe I am.

>>> Haven't had any issues calling notify outside a synchronized statement,
>>> even from multiple threads. At least this works under Win32 with my
>>> producer thread all wrapped inside synchronized(). Only a single
>>> consumer thread is inside synchronized() but then i have 2 more threads
>>> making naked calls to notify(). Not a single crash.
>>
>> Doesn't prove anything, it could happen that you just miss a
>> notification, for instance. Another common case is that it so happens
>> that wait will (with luck) always happen before any of notify and
>> notifications come spaced out in time.
>
> I don't see how you could miss a notification, can you explain further?

Not particularly well put. In general I was implying that program not 
crushing doesn't mean anything useful. It might work either due to 
happenstance. Depending on the implementation of notify, if it's not 
re-entrant then technically anything fishy can happen.

-- 
Dmitry Olshansky


More information about the Digitalmars-d-learn mailing list