synchronized (this[.classinfo]) in druntime and phobos
Steven Schveighoffer
schveiguy at yahoo.com
Wed May 30 10:47:05 PDT 2012
On Wed, 30 May 2012 13:12:47 -0400, Andrei Alexandrescu
<SeeWebsiteForEmail at erdani.org> wrote:
> On 5/30/12 9:23 AM, Alex Rønne Petersen wrote:
>> On 30-05-2012 18:14, Andrei Alexandrescu wrote:
>>> This is news to me. How do you publicly access the mutex of a
>>> synchronized class object?
>>
>> Generally in two ways:
>>
>> 1) synchronized (obj)
>
> This is not accessing the mutex for arbitrary operations.
If I might interject, I think the issue is that as the author of a class,
you cannot enforce that *only* the data in your class is protected by the
mutex.
Yes, you can enforce that the data is protected, but there is nothing
stopping a 3rd party caller from hijacking your mutex to protect other
things it shouldn't be involved with.
For instance, let's say you have:
synchronized class A
{
private int _foo;
@property int foo() { return _foo;}
}
synchronized class B
{
private A _a;
@property A a() { return _a;}
void fun() {}
}
void thread(B b)
{
synchronized(b.a)
{
b.fun();
}
}
Run multiple instances of this thread, and it will deadlock. As the
author of A, you have no control for preventing external code from
hijacking your mutex for its own purposes in an incorrect way.
But take out this public access to your mutex, and you *can* enforce A's
locking semantics correctly, and therefore B's semantics. Absolutely no
way can A or B's lock participate in a deadlock.
I think it is worth making this enforceable. In other words, the
synchronized(b.a) statement shouldn't compile.
Yes, you can just use a private mutex. But doesn't that just lead to
recommending not using a feature of the language? Besides, I really like
the synchronized block keyword thing. It's a great mechanism for locking.
-Steve
More information about the Digitalmars-d
mailing list