www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Multiple while-loops parallelism

reply "Mineko" <uminekorox gmail.com> writes:
Today I'm asking a more theoretical question, since I can't quite 
grasp this one too well.

Let's say I want 3 while-loops running in parallel, without 
getting in the way of each other, how would I do that?

With std.parallel of course, but that's where I get confused, 
perhaps someone could enlighten me?
Jan 17 2014
next sibling parent "Stanislav Blinov" <stanislav.blinov gmail.com> writes:
On Friday, 17 January 2014 at 21:07:46 UTC, Mineko wrote:

 Let's say I want 3 while-loops running in parallel, without 
 getting in the way of each other, how would I do that?
On the same set of data? That's optimistic if one of the loops writes :) Otherwise, you could just create three tasks, one per loop.
Jan 17 2014
prev sibling parent reply "Kelet" <kelethunter gmail.com> writes:
On Friday, 17 January 2014 at 21:07:46 UTC, Mineko wrote:
 Today I'm asking a more theoretical question, since I can't 
 quite grasp this one too well.

 Let's say I want 3 while-loops running in parallel, without 
 getting in the way of each other, how would I do that?

 With std.parallel of course, but that's where I get confused, 
 perhaps someone could enlighten me?
Hi,
 std.parallel
You mean std.parallelism. Assuming your code is thread safe[1], you would have each of these while loops in a delegate or function, and create a Task[2]. Once the Task is created, use the executeInNewThread function. You can use yieldForce to wait on it. However, if you don't *really* need while loops, take a look at creating a TaskPool and using a parallel foreach, reduce, map, etc. They are also in std.parallelism. However, it's worth noting that there is also std.concurrency[3] which may be a better approach if your threads need to communicate. core.thread/core.atomic are useful if you need lower level control. If your code is not thread safe, look into synchronized statement, core.atomic, and possibly core.sync.* and make it thread safe. [1]: http://en.wikipedia.org/wiki/Thread_safety [3]: http://dlang.org/phobos/std_concurrency.html Regards, Kelet
Jan 17 2014
parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 01/17/2014 01:28 PM, Kelet wrote:

 create a Task[2]. Once the Task is created, use the executeInNewThread
 function. You can use yieldForce to wait on it.
That's what I thought initially as well but then I realized that it can be even simpler than that: import std.stdio; import std.parallelism; void main() { // All of these loops can be free-standing functions as well long sum1 = 0; auto loop1 = { foreach (number; 0 .. 100) { sum1 += number; } }; long sum2 = 0; auto loop2 = { foreach (number; 0 .. 100) { sum2 += number; } }; foreach (loop; [ loop1, loop2 ].parallel) { loop(); } writefln("sum1: %s, sum2: %s", sum1, sum2); } Ali
Jan 17 2014