Meta-programming - examples

janderson askme at me.com
Sat Feb 10 22:54:30 PST 2007


Andrei Alexandrescu (See Website For Email) wrote:
> janderson wrote:
>> Andrei Alexandrescu (See Website For Email) wrote:
>>> janderson wrote:
>>>> Multi-threading
>>>>
>>>> The suggestion with multi-threading I came up with a little while ago:
>>>>
>>>> int[] array ...
>>>> int result = 0;
>>>> mixin(threadIt(
>>>> "
>>>>     foreach(A a; array)
>>>>     {
>>>>         result += a;
>>>>     }
>>>>     combiner //If necessary?
>>>>     {
>>>>         result = result[0] + result[1];
>>>>     }
>>>> ");
>>>>
>>>> Compile time checking of code for coding standards or what have u:
>>>
>>> I'm not understanding this.
>>
>> What part?
> 
> The multi-threading part.

Essentially the code would be-reformated to take advantage of 
multi-cpus.  The code generator threadIt would make a copy of all 
variables used inside of the foreach and run a partial foreach on each 
thread.  The combiner bit is run on each thread until they all collapse 
together (
ie  in this case
resultA = resultofThreadA + resultofThreadB;
resultB = resultofThreadC + resultofThreadD;
result = resultA + resultB; //Final result
)

Of course it goes without saying that each iteration in for for-each 
must be independent of one another (to some extent).  The advantage 
being, you see a foreach, and you can just wrap it in "mixin(threadIt(" 
to get a performance boost.  Looking though some of my C++ code, I'd say 
30% of those loops could be mutli-threaded with very little (if any) 
changes with the above approach.

The basic thought is that you could prove ideas work before even sending 
a message to the newsgroup.

> 
> Andrei



More information about the Digitalmars-d mailing list