Multicore
Aspects
Applications to run faster if we have multicore CPUs
- Alternatively, several CPUs in a distributed setting
Is the code going to run faster just by having more cores?
No!
It might if it has lots of non-interferent processes and no sequential bottlenecks
Erlang uses all the cores on the SMP machine by default
Symmetric MultiProcessing
erl -smp +S N
The number
N
indicates how many schedulers (govern Erlang virtual machines)Useful to test how the program works on different amount of cores
Speeding up programs on a multicore CPU
General guidelines
Use lots of processes
- To keep cores busy!
Avoid side effects
- Their order might change in the parallel version
Avoid sequential bottlenecks
- If the algorithm is intrinsically sequential, there is no much to do
Write “small messages, big computations” code.
- If computations are very small, it might be bigger the cost of spawning and messaging among processes
Making code run in parallel
- Definition of
map
map(_, []) -> []; map(F, [H|T]) -> [F(H)|map(F, T)].
- Can the application for each element be done in parallel?
pmap(F, Xs) -> S = self(), Ref = make_ref(), Pids = map(fun(X) -> spawn( fun() -> S ! {self(), Ref, F(X)} end ) end, Xs), gather(Pids, Ref). gather([Pid|T], Ref) -> receive {Pid, Ref, Ret} -> [Ret|gather(T, Ref)] end ; gather([], _) -> [].
map(F,L) =:= pmap(F,L)
Order of elements?
Side-effects?
What if the list is very big and the computation
F
very small?