On 11/10/2011 10: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.


There is no checkable type safe way to do this (because the type system is not powerful enough). You have to use type casts and work for the correctness guarantees yourself:


class Foo
{

}

void worker( shared(Foo[]) data_ )
{
Foo[] data = cast() data_; // this cast is valid because data_ is never read from another thread after the cast
    //...
}

void main()
{
    {
        auto data = new Foo[10];
spawn( &worker, cast(shared)data ); // this cast is valid because data is an unique reference (therefore there are no unshared aliases) } // the sole reference to data in the main thread dies -> it will never be read from this thread again
}



Reply via email to