Scientific computing and parallel computing C++23/C++26
Petar
Petar
Thu Jan 13 21:16:53 UTC 2022
On Thursday, 13 January 2022 at 20:07:51 UTC, forkit wrote:
> On Thursday, 13 January 2022 at 01:19:07 UTC, H. S. Teoh wrote:
>>
>> ..... But still, it doesn't have to be as complex as languages
>> like C++ make it seem. In the above example I literally just
>> added ".parallel" to the code and it Just Worked(tm).
>>
>>
>> T
>
> I wish below would "just work"
>
>
> // ----
> module test;
>
> import std;
>
> @safe
> void main()
> {
> //int[5] arr = [1, 2, 3, 4, 5]; // nope. won't work with
> .parallel
> int[] arr = [1, 2, 3, 4, 5];// has to by dynamic to work
> with .parallel ??
>
> int x = 0;
>
> foreach(n; arr.parallel) // Nope - .parallel is a @system
> function and cannot be called in @safe
> {
> x += n;
> }
>
> writeln(x);
> }
> // -----
```d
import core.atomic : atomicOp;
import std.parallelism : parallel;
import std.stdio : writeln;
// Not @safe, since `parallel` still allows access to
non-shared-qualified
// data. See:
//
https://github.com/dlang/phobos/blob/v2.098.1/std/parallelism.d#L32-L34
void main()
{
int[5] arr = [1, 2, 3, 4, 5]; // Yes, static arrays work
just fine.
// `shared` is necessary to safely access data from
multiple threads
shared int x = 0;
// Most functions in Phobos work with ranges, not
containers (by design).
// To get a range from a static array, simply slice it:
foreach(n; arr[].parallel)
{
// Use atomic ops (or higher-level synchronization
primitives) to work
// with shared data, without data-races:
x.atomicOp!`+=`(n);
}
writeln(x);
}
```
More information about the Digitalmars-d
mailing list