Modify thread-local storage from parent thread

Ali Çehreli acehreli at yahoo.com
Tue Aug 9 13:57:50 PDT 2011


On Tue, 09 Aug 2011 20:37:04 +0000, Ali Çehreli wrote:

>> 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.

The following is a program that uses std.concurrency. In this case the 
threads communicate with each other:

import std.stdio;
import std.concurrency;

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

    /* Spawn the threads */
    foreach (i, ref buffer; buffers) {
        spawn(&worker, thisTid, i, &buffer);
    }

    /* Collect the results */
    foreach (i; 0 .. buffers.length) {
        size_t id = receiveOnly!size_t();
        writefln("thread %s is done", id);
    }

    writeln(buffers);
}

void worker(Tid owner, size_t myId, ubyte[8] * buffer)
{
    foreach (ref b; *buffer) {
        b = cast(ubyte)myId;
    }

    owner.send(myId);
}

Ali


More information about the Digitalmars-d-learn mailing list