pass array of objects to spawn

Ali Çehreli acehreli at yahoo.com
Thu Nov 10 14:23:26 PST 2011


On 11/10/2011 01:57 PM, Ruslan Mullakhmetov wrote:
> On 2011-11-11 01:21:09 +0400, Ali Çehreli said:
>
>> class Foo
>> {
>>
>> }
>>
>> void worker( shared(Foo)[] data )
>> {
>> //...
>> }
>>
>> void main()
>> {
>> auto data = new shared(Foo)[10];
>> spawn( &worker, data );
>> }
>
>
> Thanks. I tried to use the second version, a lttle bit modified it for
> actual mutation and it is failed to compile with error
>
> thread.d(17): Error: function thread.Foo.mutate () is not callable using
> argument types () shared
>
>
> the code:
>
> import std.exception;
> import std.concurrency;
>
> class Foo
> {
> public int val;
>
> void mutate()
> {
> val = 1;
> }
> }
>
>
> void worker( shared(Foo)[] data )
> {
> data[0].mutate();
> //...
> }
>
> void main()
> {
> auto data = new shared(Foo)[10];
> spawn( &worker, data );
> }
>
>

Some of this is black magic for me. Timon's casts help:

import std.concurrency;

class Foo
{
     public int val;

     void mutate()
     {
         val = 1;
     }
}


void worker( shared(Foo)[] data_arg )
{
     auto data = cast(Foo[])data_arg;
     data[0].mutate();
     //...
}

void main()
{
     auto data = new shared(Foo)[10];

     foreach (ref element; data) {
         element = new shared(Foo);
     }

     spawn( &worker, data );
}

Ali



More information about the Digitalmars-d-learn mailing list