synchronized keyword

Walter Bright newshound at digitalmars.com
Thu Mar 22 03:10:43 PDT 2007


Robert Libby wrote:
> I'm relatively new to D, but I’d just like to say kudos to Mr. Bright for
> creating such a wonderful language!
> 
> I just ran across an interesting issue.  I may have missed something somewhere,
> but, I had a function inside of a class declared:
> 
> public class Logger {
> ..
> public synchronized void log(char s[]) {
> printf("The log entry is %.*s\n", s);
> }
> ..
> }
> 
> I was under the impression that this would safely lock a mutex so that it would
> be thread safe (as it would in Java).  However, I found instances where the
> output of two threads were happening at the same time, producing garbled output.
> 
> I changed the code to:
> public void log(char s[]) {
> synchronized {
> printf("The log entry is %.*s\n", s);
> }
> }
> 
> Which seemed to work as expected.

synchronized as a statement with no object in () means it syncs on a 
global mutex.

> So my question is, what does putting synchronized in the declaration do,

It synchronizes on the instance of Logger. You can see it in the 
generated code (try running obj2asm on it).

> and why
> doesn't it give a warning or error if it is not supposed to be there?

It not working on your code suggests that two different instances of 
Logger were calling log?



More information about the Digitalmars-d mailing list