pass array of objects to spawn

Timon Gehr timon.gehr at gmx.ch
Thu Nov 10 14:50:53 PST 2011


On 11/10/2011 11:23 PM, Ali Çehreli wrote:
> 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
>


class Foo
{
     public int val;

     void mutate() shared
     {
         val = 1;
     }
}

But you really really only want the shared modifier to persist after 
message passing if the data is not owned by a single thread afterwards.






More information about the Digitalmars-d-learn mailing list