An error on trying to sort shared data using slice
Ali Çehreli
acehreli at yahoo.com
Mon Jan 28 13:04:59 PST 2013
On 01/28/2013 12:33 PM, Sparsh Mittal wrote:
> My requirement is to sort a portion of an array in each thread, such
> that there is no overlap b/w portions and all portions together make the
> whole array.
>
> So I am taking array as shared. Currently, in each thread, I am taking a
> slice of that array to sort, although that slice is not shared, I am
> forced to take shared since compiler does not allow without it.
As I understand it, that's how it should work.
> Can you suggest something, e.g. sorting only a portion of an array,
> without slicing? Thanks.
Why not slicing? The following program probably what you have tried
anyway. It is shamefully unmaintainable: :)
import std.stdio;
import std.concurrency;
import std.algorithm;
struct Done
{}
void sorter(Tid owner, shared(int)[] sliceToSort)
{
sort(sliceToSort);
owner.send(Done());
}
void main()
{
shared numbers = [ 6, 5, 4, 3, 2, 1 ];
spawn(&sorter, thisTid, numbers[0 .. $ / 2]);
spawn(&sorter, thisTid, numbers[$ / 2 .. $]);
receiveOnly!Done();
receiveOnly!Done();
writeln(numbers);
}
Both halves of the slice are sorted:
[4, 5, 6, 1, 2, 3]
Instead of making 'numbers' itself shared, you can cast the slices that
you send to the workers as such:
auto numbers = [ 6, 5, 4, 3, 2, 1 ];
// ...
spawn(&sorter, thisTid, cast(shared)numbers[0 .. $ / 2]);
But then the rest of the code would not know that the elements of
'numbers' may be modified by other threads. Defining it as 'shared'
makes it impossible to ignore that fact.
Ali
More information about the Digitalmars-d-learn
mailing list