On Tuesday, March 06, 2018 18:34:34 bauss via Digitalmars-d-learn wrote:
> On Monday, 5 March 2018 at 19:51:33 UTC, Steven Schveighoffer
> > 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.
I confess that I've never really understood why some folks dislike
singletons so much, but then again, I've only rarely found cases where I
thought that they made sense, and I gather that some folks out there use the
singleton pattern way too much (I've heard it suggested that it's because it
was one of the few design patterns from the design pattern book that was
easy). In fact, one of my coworkers was telling me at one point about how
someone had argued to him about how a "doubleton" pattern made sense, which
just seems crazy to me, but I've found that a disturbingly large percentage
of programmers are not what I would consider competent.
I think that the singleton pattern should be used when it really makes sense
to use it, but in most cases, there's no reason to restrict the type to a
singleton. And I expect that the dislike for singletons comes from them
being used far too often when it clearly made no sense.
The one place that I can think of that I've used singletons in the last
decade or so is with the LocalTime and UTC classes for time zones (both in
std.datetime and in the C++ version that I wrote for work at one point).
Having multiple instances of those classes made no sense and would have been
pointlessly inefficient. But at the moment, that's the only case I can think
of where I've used singletons. They just don't make sense very often.
- Jonathan M Davis