www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - std.parallelism and map questions

reply "freeman" <frmn_s to_mail.com> writes:
std.parallelism uses the foreach loop for parallel().  As  such,
how might I implement a parallel while-loop?  Can I use an
ordinary for-loop with parallel()?

Also, how can I map array elements with a conditional like if()?
Sep 15 2012
parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 09/15/2012 08:12 PM, freeman wrote:
 std.parallelism uses the foreach loop for parallel(). As such,
 how might I implement a parallel while-loop?

That doesn't sound right to me because the while loop condition is normally a result of the operations inside the loop itself. And that's a race condition, violating a fundamental rule of parallelism that the operations are indepentent (having no side-effects). Perhaps I am wrong; then I would like to learn about the answer.
 Can I use an
 ordinary for-loop with parallel()?

I think this works: import std.stdio; import std.parallelism; import core.thread; void foo(size_t i) { writefln("Working on %s", i); Thread.sleep(dur!("msecs")(500)); } void main() { auto workers = new TaskPool(2); for (size_t i = 0; i != 10; ++i) { if (i != 7) { auto t = task!foo(i); workers.put(t); } } workers.finish(); }
 Also, how can I map array elements with a conditional like if()?

You can pass the return range of std.algorithm.filter to map: import std.stdio; import std.parallelism; import std.range; import std.algorithm; int tenTimes(int i) { return i * 10; } void main() { auto result = taskPool.map!tenTimes(iota(10).filter!(a => a % 2)(), 5); writeln(result); } Ali
Sep 15 2012