Static constructor

ludo fakeaddress at gmail.com
Tue Jan 12 11:28:12 UTC 2021


NOTE : the entire code we are talking about is in the tiny url in 
my previous post.

On Thursday, 7 January 2021 at 01:55:07 UTC, SealabJaster wrote:
> On Wednesday, 6 January 2021 at 17:05:02 UTC, ludo wrote:
>> ...
>
> Using a static class like this seems to mostly be a design 
> decision.
> So in otherwords, this class is essentially being used as a 
> unique namespace for all of the other functions. Another way to 
> look at it is just a singleton without a `.instance` getter.

Ok, I agree that ends up being a kind of strange singleton. But 
yes it was D v1 code. Do we agree that the following 
multi-threaded singleton pattern is the proper way as of today, 
instead of this static functions in a non static class (in 
multithreaded environment)?
----
shared(T) singleton()
{
  static shared T instance;

  if(!instance)
  {
    synchronized
    {
      if(!instance)
      instance = new shared(T)();
    }
  }

  return instance;
}
---

>
> As for some of the other stuff, Associative Array literals in D 
> can't actually be used at compile-time (at least, last time I 
> tried), so they have to be created inside of the static 
> constructor.

OK, I found 
https://dlang.org/spec/hash-map.html#static_initialization
Quote from that doc:
"Static Initialization of AAs
  NOTE: Not yet implemented. "
If I understand, as of today an AA init depends on a runtime 
function for historical reasons. A bit weird for an array indeed 
perfectly known at compile time, but someday some  core language 
contributor will have a look at it, I guess.

>
> Next is the mutex. `Object` is the base class that every class 
> in D will implicitly inherit from, like in C# for example. 
> Object has a `.monitor` field which is basically just a mutex, 
> so is used with multi-threading synchronisation. I find it a 
> bit odd that they're just returning an object instead of a 
> Mutex (module core.sync.mutex), but I'm sure there's a reason 
> why.

If we consider the class from my first post, the comment coming 
with the getMutex func is following in the original code that I 
am "cleaning-up":
"Get an OpenAL mutex to ensure that no two threads ever execute 
OpenAL functionality simultaneously."

But the OpenAL class only has one function (anotherFunc), and as 
you say SealabJaster, it looks odd to use this Object mutex. I 
see two options to replace this mutex thing:
* make the entire class synchronized (writing "synchronized class 
OpenAL")
* make the anotherFunc function synchronized. So just one keyword 
to add!
If I understand well, this will accomplish the goal quoted with 
no further comestics needed! Only one keyword over explicitely 
using object mutex. Am I right?

Thanks



More information about the Digitalmars-d-learn mailing list