A monitor for every object

Steven Schveighoffer schveiguy at yahoo.com
Mon Feb 7 04:48:53 PST 2011


On Sat, 05 Feb 2011 05:51:35 -0500, spir <denis.spir at gmail.com> wrote:

> Steven Schveighoffer:
>
>> D's monitors are lazily created, so there should be no issue with  
>> resource
>> allocation.  If you don't ever lock an object instance, it's not going  
>> to
>> consume any resources.
>
> For the non-sorcerers following the thread, would someone explain in a  
> few words what it actually means, conceptually and concretely, for an  
> object to be its own monitor. (searches online have brought me nothing  
> relevant)

A monitor is used for concurrency.  Essentially, it is a mutex (or  
critical section on Windows).  When you do this:

class C
{
    synchronized void foo() {}
}

The synchronized keyword means a call to foo will lock the embedded  
monitor before calling it.

The meaning of an 'object being its own monitor' is just that the monitor  
for operations on an object is conceptually the object itself (even though  
it's technically a hidden member of the object).

This model has some very bad drawbacks, because it encourages you to use  
an object to lock an operation on itself when most cases, you want more  
coarse mutexes (mutexes should be tied to entire concepts, not just to  
individual objects).

With D, you can alleviate this somewhat by specifying a specific monitor  
for an object.

To explain my statement in real-world terms, the monitor is essentially a  
resource handle (on linux, this is a pthread_mutext_t) that begins life as  
null.  When an object is locked for the very first time, some low-level  
atomic code checks to see if the monitor is allocated and if not, creates  
a pthread mutex and assigns it to that hidden monitor field.

Once the monitor is created, it's used from now on.  What I meant by lazy  
creation is that simply creating an object doesn't also consume a mutex  
resource + degrade performance.  It's only on the first lock that you have  
to worry about it.

-Steve


More information about the Digitalmars-d mailing list