What sync object should i use?
Steven Schveighoffer
schveiguy at yahoo.com
Tue May 14 12:29:45 PDT 2013
On Tue, 14 May 2013 15:19:29 -0400, Sean Kelly <sean at invisibleduck.org>
wrote:
> If you move the notify out of the mutex then you can end up with
> multiple threads competing for the same value. Say the producer puts a
> value in the queue, leaves the mutex, and notifies a waiting thread.
> Then consumer A enters the mutex, sees that there's something in the
> container and takes it, then consumer B receives the notification and
> wakes up to discover that the container is empty. So long as your wait
> loops are done properly the only bad result will be pointless wakeups,
> but worst case you could have a crash or exception if you're removing
> data from the container without checking if it's empty.
Any thread that does not check to ensure his data is ready while waiting
for a condition, I would argue is incorrectly implemented -- cond.notify
is not directly tied to the data, and there's always cond.notifyAll which
could wake up any number of threads.
I also don't think there's a requirement that threads waiting on a
condition have priority over threads simply trying to lock.
But I see little reason to avoid putting the cond.notify inside the lock.
You HAVE to lock to insert the data anyway.
And Dmitry seems to have some Java experience that indicates it's at least
required there. I'd say go with notifying only while locked.
I learn something every day :)
-Steve
More information about the Digitalmars-d-learn
mailing list