pass array of objects to spawn

Ali Çehreli acehreli at yahoo.com
Thu Nov 10 13:21:09 PST 2011


On 11/10/2011 01:06 PM, Ruslan Mullakhmetov wrote:
> Hi folks,
>
> I need to create thread and pass to it array of objects wich will no
> longer use in main thread.
>
> The problem is that spawn only accepts immutables and i have no idea how
> to tell him that i transfer full ownership of the data to child thread.
>
> the code:
>
> import std.concurrency;
>
> class Foo
> {
>
> }
>
> void worker( Foo[] data )
> {
> //...
> }
>
> void main()
> {
> auto data = new Foo[10];
> spawn( &worker, data );
> }
>
>
> P.S. I do need to create data in main thread and distribute it to child
> threads.
>

I haven't tested these at runtime, but they compile:

1) (This is not actually what you want, as you want to mutate the array 
further in the worker.)

Take array as 'immutable' and use assumeUnique (I don't know why it's a 
part of std.exception :)):

import std.exception;
import std.concurrency;

class Foo
{

}

void worker( immutable(Foo)[] data )
{
     //...
}

void main()
{
     auto data = new Foo[10];
     spawn( &worker, assumeUnique(data) );
}

2) Make data 'shared' and take the responsibility of ownership and sharing:

import std.exception;
import std.concurrency;

class Foo
{

}

void worker( shared(Foo)[] data )
{
     //...
}

void main()
{
     auto data = new shared(Foo)[10];
     spawn( &worker, data );
}

Ali


More information about the Digitalmars-d-learn mailing list