Static constructor

Steven Schveighoffer schveiguy at gmail.com
Mon Jan 18 14:30:48 UTC 2021


On 1/17/21 6:54 PM, ludo wrote:
> Yes alright. I think the dev made a design mistake because he called 
> synchronized( OpenAL.mutex ) when it should be more of a global, non 
> OpenAL specific, mutex. I mean in the code there were things like  
> (pseudo-code)
> ---
> System {
>    private int[] buffer
> 
>    func() {
>      synch (openal.mutex)
>      {
>        openal.dosmthg (buffer)
>        buffer.change() // buffer being the member of System
>        openal.dosmthg(buffer)
>      }
>    }
> }
> ---
> Basically, it's the entire buffers handling ( the 3 statements) which 
> should be done the "atomic" way, not just the calls to openAL. So the 
> mutex should be a member variable of System at worse. I just replaced
> synchronized ( openal.mutex )  {
> by
> synchronized { // create a global mutex
> 
> Of course synchronized (open.mutex) would probably work, but getting the 
> mutex of an abstract class which is used only in part of the calls looks 
> like a design error to me!

Not sure if this is right. If the mutex should be protecting *more* then 
you should move the scope of the mutex out of the object into module 
space (and make it shared so it actually is used across threads).

Your code there allocates a mutex for that specific block, and nothing 
else. The mutex isn't more "global", it's more "local" (although, this 
will make it shared).

I'd follow some rules like:
1. If the mutex is for one specific block and does not need to be locked 
for any other code, then use a naked synchronized command. This is an 
odd case, because it is for a specific block of code, but works across 
all calls of that code. So the data it protects needs to be only used in 
that code, but also used across all instances of the objects. I'd use 
this one rarely.
2. If the mutex is for data in a specific object, make it a member of 
that object (or use the object itself as the mutex).
3. If the mutex is for static data in an object that is shared between 
threads, make it a shared static member of that object.
4. If the mutex is for static data in multiple objects, then put it in 
the module as a shared data item.

-Steve


More information about the Digitalmars-d-learn mailing list