pass array of objects to spawn

Ruslan Mullakhmetov tiabaldu at gmail.com
Thu Nov 10 22:33:02 PST 2011


On 2011-11-11 02:48:52 +0400, Timon Gehr said:

> On 11/10/2011 11:00 PM, Ruslan Mullakhmetov wrote:
>> On 2011-11-11 01:23:01 +0400, Timon Gehr said:
>> 
>>> 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
>>> }
>> 
>> Thank you too. Unfortunately i got compilation error
>> 
>> thread.d(16): Error: cannot implicitly convert expression (data_) of
>> type shared(Foo)[] to Foo[]
>> 
>> 
>> 
> 
> Interesting, apparently cast() does not remove shared. Sorry about 
> that, use this (this time I tested it).
> 
> import std.concurrency;
> 
> class Foo
> {
> 
> }
> 
> void worker( shared(Foo[]) data_ )
> {
>      auto data = cast(Foo[]) data_;
>      //...
> }
> 
> void main()
> {
>      {
>          auto data = new Foo[10];
>          spawn( &worker, cast(shared)data );
>      }
> }

thank you very much. For now it's working. But it would be quite 
interesting to add explicit ownership semantics to the language as Ali 
sugested once by keyword unique.

By the way, I realized that it would be better to create data in thread 
rather pass it to thread and pass some seeds for creating data. Of 
course, this is one case, sometimes transfer of ownership is not 
avoidable as it seems to me.
-- 
BR, Ruslan Mullakhmetov



More information about the Digitalmars-d-learn mailing list