Does anyone understand how to use "shared" types with concurrency send/receive functions?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Aug 15 14:54:23 PDT 2017


On 8/15/17 5:27 PM, Arek wrote:
> On Tuesday, 15 August 2017 at 10:37:08 UTC, Kagamin wrote:
>> Well, no wrapper is actually needed here:
>>
>> class A
>> {
>>     int method() shared;
>> }
>>
>> void consumer()
>> {
>>     shared a = receiveOnly!(shared A)();
>> }
>>
>> void producer()
>> {
>>     auto cons = spawn(&consumer);
>>     send(cons, new shared A());
>> }
> 
> Yes, but this doesn't compile:
> 
> import std.stdio;
> import std.concurrency;
> 
> struct A
> {
>      int t;
>      int r;
>      int method() shared
>      {
>          return 0;
>      }
> }
> 
> void consumer()
> {
>      shared a = receiveOnly!(shared A)();
> }
> 
> void main()
> {
>      auto cons = spawn(&consumer);
>      send(cons, shared A());
> }

The issue is that send cannot handle shared value types due to a bug in 
the implementation. In essence, there is no reason to send a shared A -- 
it's an unrelated copy and not actually shared.

You can send a shared reference to an A just fine:

static shared A a;

send(tid, &a); // works

You *should* be able to send a shared(A). There is no reason to disallow 
it. But again, it's not super useful.

> This very simple code also doesn't compile:
> 
> shared struct S
> {
>      int i;
> 
>      ~this()
>      {
>      }
> }
> 
> void main()
> {
>      shared s = shared S();
> }
> 
> In general, shared structs with postblit and destructor make problems.

postblit should work.

It does look like destructors are a problem. It appears the compiler 
attempts to call the destructor while unshared.

-Steve


More information about the Digitalmars-d-learn mailing list