Is synchronized(...){...} doomed to never be nothrow/@nogc?

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Tue May 10 16:29:00 PDT 2016


On Tuesday, May 10, 2016 17:46:17 Vladimir Panteleev via Digitalmars-d wrote:
> Here is the situation, AIUI:
>
> 1. We allow users to provide their own Monitors, which hook into
> the synchronized(obj) statement.
>
> 2. These monitors' methods are unadorned (no nothrow/@nogc).
>
> 3. As a result, synchronized(obj) statements will not compile in
> nothrow/@nogc code, because we can't know that the Monitor
> implementation doesn't throw / use the GC.
>
> 4. As Matthias mentioned, fixing this was attempted before (by
> making the Monitor methods `nothrow`). However, this broke code
> (vibe.d specifically), as its implementation was actually not
> `nothrow`: https://issues.dlang.org/show_bug.cgi?id=11216
>
> This is a problem e.g. in Druntime code, because it currently
> forces a lot of code that should be `nothrow` to not be annotated
> as such, even when the synchronization objects used use the
> standard D monitor implementation, which is actually `nothrow`.
>
> So I guess the way forward here for the Druntime code is to
> abandon the synchronized() statement and use locks directly?

Well, if polymorphism is involved at all, we're going to be screwed one way
or another with regards to attributes. Either we're going to be very
restrictive about what can be done in those functions by marking them with
attributes like @nogc and nothrow, or we're giong to be restrictive about
what code can use those functions by not marking them with attributes like
@nogc or nothrow. This is part of why inheritance and polymorphism tend to
be a very bad idea in D. OOP can obviously be very useful, but it comes at a
definite cost.

The only way to fix it so that we don't force one set of attributes or
another would be to stop using polymorphism, and make it so that all of the
code involved can be examined at compile time. So, either we figure out how
to do that, or we have to pick which attributes we want and deal with the
restrictions that come with them.

That being said, I have a hard time believing that it makes sense for these
primitives to involve exceptions - and even the GC likely shouldn't be
involved, particularly since these aren't the sorts of operations that would
normally allocate. So, I would think that aside from the breakage it would
cause, marking them as @nogc and nothrow would be perfectly acceptable. The
problem is that changing the attributes on a class or interface tends to
result in immediate code breakage, and I'm not sure that we really have a
fix for that.

- Jonathan M Davis



More information about the Digitalmars-d mailing list