Does anyone understand how to use "shared" types with concurrency send/receive functions?
Kagamin via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Aug 15 03:33:18 PDT 2017
On Monday, 14 August 2017 at 22:22:58 UTC, Arek wrote:
> I've found some simple workaround for this problem:
>
> import std.stdio;
> import std.concurrency;
>
> struct Envelope(T) if (is(T == class)) // for simplicity of
> this example, only classes
> {
> shared(T)[] obj;
>
> this(shared T o)
> {
> this.obj = [o];
> }
>
> T get() @property nothrow @nogc
> {
> return cast() obj[0];
> }
> }
>
> class A
> {
>
> }
>
> void consumer()
> {
> auto r = receiveOnly!(Envelope!(A))();
> writeln("Got: ", typeof(r).stringof);
> }
>
> void main()
> {
> auto cons = spawn(&consumer);
> auto o = Envelope!A(new A());
> send(cons, o);
> }
>
> Shared object can be encapsulated in the array. In case of
> other (non-class) types the pointer can be used, and get()
> should return ref to the pointed object (after stripping off
> the shared qualifier).
Rather like this:
struct Sendable(T)
{
shared T o;
alias o this;
}
import std.concurrency;
class A
{
int method() shared;
}
void consumer()
{
shared A a = receiveOnly!(Sendable!(A))();
}
void producer()
{
auto cons = spawn(&consumer);
shared A a = new shared A();
send(cons, Sendable!A(a));
}
More information about the Digitalmars-d-learn
mailing list