On Thu, 14 Jul 2011 14:26:04 -0400, David Nadlinger <s...@klickverbot.at> wrote:

A quick idea I just had, feel free to shoot it down if I missed something obvious:

I have been writing some »old-school« multi-threading code lately, and it occurred to me that most of the time, I am using condition variables like this:

---
auto fooMutex = new Mutex;
auto fooCondition = new Condition(fooMutex);

[…]

// Later in the code:
synchronized (fooMutex) {
   […]
   fooCondition.notifyAll();
   // or
   fooCondition.wait();
}
---

When actually using the condition variable, I often don't care what the underlying mutex actually is, I just want to lock it so I can wait() on the condition variable or notify() it. Thus, it would be convenient if Condition had a »mutex« property exposing the underlying mutex, to avoid having to remember which Mutex belongs to which Condition.

What do you think of it? Did I miss something? The »issue« can easily be worked around by a suitable naming convention for the pairs of Mutexes/Conditions, but still I feel a Condition.mutex property would make typical code look cleaner.

Hm... actually, we could do away with the mutex, and have the condition's monitor be the mutex:

auto fooCondition = new Condition(); // automatically generates new mutex.

synchronized(fooCondition)
{
   fooCondition.notifyAll();
   // or
   while(!someCondition)
     fooCondition.wait();
}

We could keep the current behavior (accept a mutex), but still have the mutex passed in be used as the monitor for the condition. Actually, can a mutex be used as the monitor for more than one object? Because it's possible multiple conditions can use the same mutex, so it's a legitimate concern.

Sean?  I think this is a really good idea...

-STeve

Reply via email to