www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - request: De-cleverified examples in Phobos

reply Johan Engelen <j j.nl> writes:
Hi all,
   As my D-fu is pretty bad, I have to resort to the documentation 
quite often. Just now I saw a presentation on std::future (C++) 
and was wondering how this is done using D. Very quickly, I found 
std.parallelism. The documentation explicitly writes that it can 
be used to do promise/future, nice!

But then... I can't find a _simple_ example showing how to do it! 
  Most (all?) examples are too clever and try to do some actual 
useful thing. I think at least a simpler example should be shown 
(aswell) without any details about the actual computation. So 
then I don't have to mentally strip the example-specific stuff 
from the code.
The parallel pi quadrature and the parallel quicksort examples 
are very clever and cool, but you first have to figure out what 
the quadrature/quicksort algorithm is doing, instead of just 
learning how to use std.parallelism. Those should be given as an 
advanced example, not as the only example.

In it's simplest form, my request is to transform (or add another 
example to) something like:
```
// Find the logarithm of every number from
// 1 to 1_000_000 in parallel, using the
// default TaskPool instance.
auto logs = new double[1_000_000];
foreach(i, ref elem; parallel(logs)) {
     elem = log(i + 1.0);
}
```
into
```
// Compute expensive_computation(x) for x=0..1000000, and store
// the answers in an array.
auto answers = new double[1_000_001];
foreach(i, ref elem; parallel(answers)) {
     elem = expensive_computation(i);
}
```

Back to my original problem: how to do this in D (chain of tasks)?
```
int expensiveOp_1();
double expensiveOp_2(int);
int expensiveOp_3(double);

auto future = async(expensiveOp_1)
                          .next(expensiveOp_2)
                          .next(expensiveOp_3);
// ...
auto answer = future.get();
```
and
```
int expensiveOp_1();
double expensiveOp_2_a(int); double expensiveOp_2_b(int);
int expensiveOp_3_a(double); int expensiveOp_3_b(double);

auto future = async(expensiveOp_1).share();
auto branch_a = future.next(expensiveOp_2_a).next(expensiveOp_a);
auto branch_b = future.next(expensiveOp_2_b).next(expensiveOp_b);
// ...
auto answer = branch_a.get() + branch_b.get();
```

Thanks!
   Johan
Oct 18 2016
parent bachmeier <no spam.net> writes:
On Tuesday, 18 October 2016 at 10:13:53 UTC, Johan Engelen wrote:
 Hi all,
   As my D-fu is pretty bad, I have to resort to the 
 documentation quite often. Just now I saw a presentation on 
 std::future (C++) and was wondering how this is done using D. 
 Very quickly, I found std.parallelism. The documentation 
 explicitly writes that it can be used to do promise/future, 
 nice!
[...]
 Thanks!
   Johan
Seems like a good example for http://forum.dlang.org/post/ntrnqs$sqr$1 digitalmars.com
Oct 18 2016