Thread synchronization

Sean Kelly sean at f4.ca
Wed Nov 29 16:43:47 PST 2006


JohnC wrote:
> What's the recommended way to guard static variables?
> 
> 1) synchronized by itself?
> 
>   static Object getObj() {
>     synchronized {
>       return sharedVar;
>     }
>   }
> 
> 2) synchronized on classinfo?
> 
>   static Object getObj() {
>     synchronized (typeof(sharedVar).classinfo) {
>       return sharedVar;
>     }
>   }
> 
> 3) synchronized on a static Object instance?
> 
>   static this() {
>     syncLock = new Object;
>   }
> 
>   static Object getObj() {
>     synchronized (syncLock) {
>       return sharedVar;
>     }
>   }
> 
> I've seen all these patterns used. Are they all safe?

They're all safe.  Since #1 is in a static method, it will synchronize 
on the ClassInfo object, just like you're doing manually in #2.  And #3 
just specifies a separate static object on which to synchronize.  But 
since it's static, you'll get the same effect.


Sean



More information about the Digitalmars-d-learn mailing list