On Monday, 5 March 2018 at 19:51:33 UTC, Steven Schveighoffer
wrote:
On 3/5/18 2:25 PM, Marc wrote:
Can __gshared be used instead of static in the singleton
pattern? I, comming from C++, ignorantly, have never used
_gshared so I went to static instead of (being static also
means thread-safe, as far I know)...
static in D is thread safe, because it's thread-local.
__gshared is shared between threads, so it's not thread safe,
but has the exact same type as just static data.
Can you use it for singleton? Sure, classic singleton is shared
between threads. But using thread-local data, you can solve the
singleton problem in a better way:
https://wiki.dlang.org/Low-Lock_Singleton_Pattern
Note, it still uses __gshared, which means it doesn't protect
you from race conditions when you actually USE the singleton
object. This means you need some synchronization inside the
methods.
-Steve
Singletons are always smelly code tbh.
Especially in D with thread-local storage.
I can't think of a situation where you truly need singletons in D.