Modify thread-local storage from parent thread

Ali Çehreli acehreli at yahoo.com
Tue Aug 9 13:37:04 PDT 2011


On Mon, 08 Aug 2011 12:17:28 -0600, Kai Meyer wrote:

> I am playing with threading, and I am doing something like this:
>          file.rawRead(bytes);
>          auto tmpTask = task!do_something(bytes.idup);
>          task_pool.put(tmpTask);
> Is there a way to avoid the idup (or can somebody explain why idup here
> is not expensive?)
> 
> If the logic above is expressed as:
> Read bytes into an array
> Create a thread (task) to execute a function that takes a copy of
> 'bytes' Execute the thread
> 
> I wonder if I could:
> Create a thread (task)
> Read bytes directly into the tasks' thread local storage Execute the
> thread

I don't know what copies happen behind the scenes in the following code, 
but std.paralleism is great when threads don't need to interact with each 
other:

import std.stdio;
import std.parallelism;

void main()
{
    ubyte[8][10] buffers;

    foreach (i, ref buffer; parallel(buffers[])) {
        ubyte value = cast(ubyte)i;
        workWith(value, buffer);
    }

    writeln(buffers);
}

void workWith(ubyte value, ref ubyte[8] buffer)
{
    foreach (ref b; buffer) {
        b = value;
    }
}

Notes:

- I had to give buffers[] to parallel() as it calls popFront() which my 
constant-size array can't provide. (Yes, I could have used a dynamic 
array.)

- Note the three ref's that I used; two of those are because constant-
size arrays are value types.

Ali


More information about the Digitalmars-d-learn mailing list