shared - i need it to be useful

Manu turkeyman at gmail.com
Mon Oct 15 20:53:32 UTC 2018


On Mon, Oct 15, 2018 at 1:05 PM Peter Alexander via Digitalmars-d
<digitalmars-d at puremagic.com> wrote:
>
> On Monday, 15 October 2018 at 18:46:45 UTC, Manu wrote:
> > Destroy...
>
> What you describe sounds better than what we currently have.
>
> I have at least two concerns:
>
> 1. A single producer, single consumer (SPSC) queue is necessarily
> shared, but is only safe if there is one writing thread and one
> reading thread. Is it ok if shared also requires user discipline
> and/or runtime checks to ensure correct usage?

I think you can model this differently... perhaps rather than a single
object, it's a coupled pair.
For instance, a thread-local enque object, and a separate thread-local
deque object. Those would express the 2 thread-local points of access
to queue and dequeue, and the implementation shunts between them in a
threadsafe way. I mean, it's not *really* a threadsafe primitive, so
for the whole object to be 'shared', I think that might be a
design-fail.

> 2. In your scheme (as I understand), a struct composed entirely
> of atomics would be able to implement shared methods without any
> casts, but also be completely thread *unsafe*. Is this okay?

It would be as safe as the design intends.
A struct with a bunch of public atomics effectively presents a set of
distinct atomics, and each one is thread-safe relative to eachother.
If the members are actually coupled into aggregate state, then you
make then private and methods implement the state transitions in such
a way guaranteeing atomicity.
Like I say before, the language can't "make it threadsafe" for you...
be producing a shared method, you have a responsibility to make sure
it works right.

> Example of #2:
>
> struct TwoInts {
>    Atomic!int x, y;
>
>    void swap() shared {
>      int z = x.load;
>      x.store(y.load);
>      y.store(z);
>    }
> }

Your swap function is plain broken; it doesn't do what the API promises.
You can write all sorts of broken code, and this is a good example of
just plain broken code.
Also, `x` and `y` probably shouldn't be public, or it effectively
communicates that they're de-coupled state.


More information about the Digitalmars-d mailing list