Coding challenge: 'sleep sort'!

Status
Not open for further replies.

pyu

Ars Praefectus
5,108
Subscriptor
S. Carton":32qblljp said:
In erlang:

Code:
-module(sleep_sort).
-compile(export_all).

sorter(Num) ->
	timer:sleep(Num * 1000),
	io:format("~p~n", [Num]).

sort(Num_list) ->
	lists:foreach(fun (N) -> spawn_link(?MODULE, sorter, [N]) end, Num_list).

Usage is:

Code:
Erlang R14B01 (erts-5.8.2) [source] [rq] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.8.2  (abort with ^G)
1> c(sleep_sort).
{ok,sleep_sort}
2> sleep_sort:sort([1,4,3,5,2]). 
ok
1  
2  
3  
4  
5  
3>

Cool. But you could make it more useful by collecting the results back into a list. ;)
 

fitten

Ars Legatus Legionis
55,636
Subscriptor++
MilleniX":1ztca5vv said:
BitPoet":1ztca5vv said:
Wonder what an MPI version of this would look like...

I'm not even going to try to compile or run this, but . . .

[snip.... MPI code]

If it's not obvious, this assumes one more rank than there are elements to sort.

Phil

I'd put an MPI_Barrier right before the if (rank == 0) so that all the processes sync at that point, then do the sleeps and such... not that it guarantees everything will sync precisely but it would hopefully bring them a little closer together.
 

S. Carton

Ars Scholae Palatinae
937
Cool. But you could make it more useful by collecting the results back into a list. ;)

Code:
-module(sleep_sort).
-compile(export_all).

sorter(Num, Caller) ->
   timer:sleep(Num * 1000),
   Caller ! Num.

sort(Num_list) ->
	lists:foreach(fun (N) -> spawn_link(?MODULE, sorter, [N, self()]) end, Num_list),
	collector(length(Num_list), []).

collector(0, Accum) ->
	lists:reverse(Accum);
collector(N, Accum) ->
	receive Num -> collector(N -1, [Num | Accum]) end.
 
Status
Not open for further replies.