Shared object must have synchronized interface?
Jonathan M Davis
jmdavisProg at gmx.com
Sat May 11 21:51:39 PDT 2013
On Sunday, May 12, 2013 06:34:48 Domain wrote:
> Sure, we can use synchronized block instead of synchronized
> function. But it's inconvenient. Why not the compiler
> automatically convert the non-synchronized function to
> synchronized function when the object declare as shared?
The actual code generated for a synchronized function would be different, and
automatically handling of locking like that would actually be very error-prone
- particularly when you consider the potential for deadlocks. Do you really
want to end up with deadlocks because the compiler chose to automatically
insert locks where you didn't ask for them?
Another thing to note is that on some level, shared code is _supposed_ to be
inconvenient. You shouldn't be doing it often. It's supposed to be possible
but not necessarily friendly. It's quite possible that we haven't hit the
right balance on that, and it's too much of a pain to do right, but it was
never intended that any of that be automatic or invisible. Code dealing with
shared objects should be carefully segregated from normal code.
synchronized was designed with the idea that you would create classes that
were specifcally for synchronization and not that normal code would be
synchronized. In fact, TDPL calls for making entire classes synchronized or
not rather than individual functions (though it's not currently implemented
that way in the compiler - you can still have both synchronized and
unsynchronized functions in the same class). So, if you intended to use
synchronized functions, you'd set it up so that the whole object was set up
that way and only ever used that way.
I suggest that you read the chapter on concurrency in TDPL. That particular
chapter is actually available online for free:
http://www.informit.com/articles/article.aspx?p=1609144
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list