by oblio · 5y ago · 0 comments
Is there any language where you can just go:
parallel-for:
do-my-stuff
and have the programming language Do The Right Thing with no further hassle? The right thing usually being blocking execution until every parallel do-my-stuff finishes execution, in my experience.In most programming languages I've seen this is a 20+ line boiler plate full of caveats and risks.
1: tmpA := A(input)
2: tmpB := B(tmpA)
3: tmpC := C(tmpB)
4: result := D(tmpC)
it's impossible to calculate a line before the previous line has finished. You cannot do this calculation concurrently. On the other hand if it was like this: 1: resA := A(input)
2: resB := B(input)
3: resC := C(input)
4: resD := D(input)
You can calculate all 4 concurrently and achieve a great speed-up if you have resources to do it. Except if B, C, or D somehow access the result of a previous line. For mathematical notation this is simple, but for general programming languages there are plenty of ways to do this.We know that an optimal optimization, i.e. finding the fastest way a program can be executed is known uncomputable. Not difficult, not brute forceable, but impossible to compute with traditional computers. The best we can do is identify _some_ concurrency optimizations, but so far it has not been a fruitful adventure for general programming languages. So what we can do is use patterns and constructs that rely on dividing the problems into concurrent pieces and use proper guarding on shared state. This is however notoriously easy to get wrong.
When programming the level of friction is from annoying to high unbearable, depending on the programming language. It should be trivial to implement these solutions, as trivial as the sequential solutions.
It's not. Until this is the case in mainstream programming languages, I doubt we'll have CPUs with 1000 cores in our smartphones or laptops. I mean, we'll have them but they'll be useless because 99% of software today is practically single-threaded. The reason multiple cores are good for laptops, for example, is because we're multi-tasking between multiple applications, not because those cores are frequently used by day-to-day apps. I'm talking about random small apps, not compute intensive ones that have to use multi-threading intensively (rendering, compiling, what have you, professional level software).
I used to joke developers should get workstations with SPARC Niagaras or Xeon Phis for that reason: core count is going up and a CPU with a dozen small cores is much cheaper to build than one with 4 beefy ones. Now some of the low-end chips Intel is pushing have 4 SMT2 cores. HEDT is on the 16 SMT2 core range and, if our software continues to be single threaded, there will be a lot of silicon being used for nothing more than spreading heat.
I'm really curious about the proof of this, since there's only a finite number of ways you can re-arrange instructions in a program. Likewise there's only a finite number of ways you could shard them across threads.
For this to be true you'd clearly need to phrase the problem in a way that allows you to have an infinite number of possibilities, then prove you can't arrive at the optimal solution through some means that doesn't involve checking an infinite number of them. (Edit: Or prove that it is impossible to decide on which one is the fastest at the time the optimizer runs. When does the optimizer run?).
Was the assumption that you'd also be (infinitely) unrolling loops or maybe 'rewriting' the program into something equivalent but faster? What does "finding the fastest way a program can be executed" mean? Just re-ordering instructions and distributing them across threads, or something more?
But even so, minimizing the program size is uncomputable as well. Given a Turing Machine M, create a program P(i) that simulates M for i steps and return true if the machine reaches an accepting state. If you provide an optimizing program OPT, then OPT(P) would be "return false;" if and only M does not halt. I.e. the optimizer would solve the halting problem which we know is not possible.
And not only finding parallelizable instructions either, I assume.
Thanks for the clarification, because such a proof would have surprised me a lot.
The assumptions and optimizations the optimizer is allowed to use and what kinds of programs we're talking about, and what even is considered an "optimal program" is also still unclear (Edit: I'm assuming lowest number of instructions executed serially?).
Please do refer me to a paper. Please do not link me vaguely related Wikipedia articles.
Though none of these are quite as convenient as I think they could be. I suspect there is a path for Rust to add parallel iteration syntax in the future [5]. There are quite a few steps needed to get there, but the result could look something like this:
let mut listener = TcpListener::bind("127.0.0.1:8080")?;
println!("Listening on {}", listener.local_addr()?);
par for stream? in listener.incoming() {
println!("Accepting from: {}", stream.peer_addr()?);
io::copy(&stream, &stream)?;
}
[1]: https://devblogs.microsoft.com/cppblog/using-c17-parallel-al...[2]: https://docs.rs/rayon/1.5.0/rayon/
[3]: https://dotnettutorials.net/lesson/parallel-for-method-cshar...
[4]: https://devblogs.microsoft.com/powershell/powershell-foreach...
[5]: https://blog.yoshuawuyts.com/parallel-stream/#future-directi...
If you do not include the standard library _AND_ if you use these features, then you'd need to provide your own parallel run-time or your application won't compile.
There are many valid implementations of these run-times tuned for different applications, these run-times can be as simple or complex as you'd like, in some cases some run-times only work on particular bare metal targets, and in most cases you just pull a library with the implementation that you'd want to use.
Since a valid implementation of the run-time is to just run all tasks sequentially, you can provide a tiny (often "zero-size") run-time for those environments on which code-size trumps everything.
You can also provide the standard parallel run-time, but this might require operating-system like functionality, like thread, mutex, etc. support. If your embedded target does not provide those, you'd need to provide implementations of these yourself.
The important thing is that you don't need to change any code that uses the run-time, e.g., all the app code can still use fork-join parallelism, but you control how that's executed by swapping the modular runtime component.
I'd imagine something similar could be introduced for threadpools / runtimes.
It’s not like separate parts of a program can each optimize for the number of threads and their memory for their goals. Optimization/tuning has to happen globally because the resources used (threads, memory) are shared between those parts.
I think most solutions have some global state that magically decides how many threads to run in parallel (more for I/O bound code), how many to assign to each part (which don’t even have to be perfectly separate. Part P might parallellisme a loop where each iteration calls into part Q, which also runs a parallel loop. If each of these decides to run one thread per CPU for N threads in total, the result still c/would be that N² threads run in parallel, likely with suboptimal results)
use rayon::prelude::*;
fn sum_of_squares(input: &[i32]) -> i32 {
input.par_iter() // <-- just change that!
.map(|&i| i * i)
.sum()
}Anyway, there's a language called ParaSail[0] that's doing stuff in that direction. A little bit back the guy behind it got hired by AdaCore (Ada compiler folks) and they seem to have adopted it and continuing with it. I haven't heard too much about it though.
Think of Occam programs as big Factorio factories.
https://en.wikipedia.org/wiki/Occam_(programming_language)
Alot the ideas that came out of Occam and CSP have been brought into various coroutine libraries though. Kotlin Coroutines, Goroutines, etc. So its definitely something that is explored.
Nothing prevents a map function to run in parallel.
There are other things that can happen in parallel, however - the whole instruction flow is reordered in the CPU before it is executed and if you have enough execution ports and enough in-flight instructions to keep them fed, you can accomplish a lot in a single clock cycle before your source code even needs to acknowledge that instructions don't happen exactly in the sequence they are written.
For instance 3D-API shading languages do just that under the hood, just without the "parallel-for". Instead you tell a 3D-API what code should run per-vertex or per-pixel in (usually) a traditional sequential C-style language, and the GPU driver and hardware care about the parallelization and scheduling.
You need a C/C++/fortran compiler that supports openmp, which is most of the mainstream ones (I believe MSVC still only support an older standard, still more than enough for parallel for). Compilers that do not support openmp are supposed to ignore the pragma and the code will still run fine (although serially) and be fully compatible.
Other than that and possibly passing the correct command line flag, openmp is fairly low friction. A parallel for can provide significant speedup for embassingly parallel problems and these days it even support custom random access iterators in C++.
Of course it is more involved to express less embarrassingly parallelizable problems, but it is still doable.
Multiple independent programs sending messages to each other fits well into multiple independent cores sending messages to each other.
Serial:
list.map(_ + 42)
Parallel: list.par.map(_ + 42)
In C# (https://docs.microsoft.com/en-us/dotnet/standard/parallel-pr...)Serial:
for (int i = 0; i < matARows; i++)
Parallel: Parallel.For(0, matARows, i =>
(Function takes a lambda that gets called for each value)Swift has DispatchQueue.concurrentPerform (https://developer.apple.com/documentation/dispatch/dispatchq...). That is a bit less clear and less flexible (won’t iterate over an array’s values, only over its indexes) but also fairly easy to use.
There probably are many more languages with similar constructs.
The problem is that not all problems are easy to parallelism at the algorithmic level, and for some it may be impossible.
Alongside massively multi core chips I would also love to see more efforts to push the envelope on single threaded performance.
Arrays.asList("hello", "world").parallelStream()
.forEach(s -> System.out.println(s));
If you want to calculate stuff, you can List<String> suffixed = Arrays.asList("hello", "world").parallelStream()
.map(s -> s + "_suffix")
.collect(Collectors.toList())As to languages built around this, there are quite a few, e.g. Intel have Data Parallel C++
But not every problem (i.e. the Algorithm for the problem) can be divided easily without any coordination (i.e. communication) between the chunks. This overhead can quickly become significant.
There is a reason why desktop software (particularly the computationally intensive) is having a hard time exploiting multi-core benefits (besides the programming language and habits in general).
Of course when you start doing things in parallel there are automatically a number of caveats and risks.
It gets difficult once you have side effects and/or synchronization (join) of the results are required.
From the docs:
The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.
Yes, but functional languages solve this problem.