Coding challenge: 'sleep sort'!

Status
Not open for further replies.

Bhelyer

Well-known member
2,231
Based on a thread I saw on reddit, I thought this would be an interesting way to see some simple concurrency stuff.

Basically, sort a list of integers by spawning a new thread or process for each element then sleep for the value of that element then print out that element. As you can imagine, this 'algorithm's' upper bound can be somewhat... concerning.

So, from the original thread (in BASH):

Code:
#!/bin/bash
function f() {
    sleep "$1"
    echo "$1"
}
while [ -n "$1" ]
do
    f "$1" &
    shift
done
wait

Code:
 example usage:
./sleepsort.bash 5 3 6 3 6 3 1 4 7

But of course, I had to take a crack at it myself: (In D)

Code:
import core.thread;
import std.algorithm;
import std.array;
import std.concurrency;
import std.conv;
import std.stdio;

void f(Tid parent, int n)
{
    Thread.sleep(dur!"seconds"(n));
    writeln(n);
    send(parent, thisTid());
}

void main(string[] args)
{
    Tid spawnf(string arg) { return spawn(&f, thisTid(), parse!int(arg)); }
    auto tids = array( map!spawnf(args[1 .. $]) );

    auto tidsRemaining = tids.length;
    while (tidsRemaining > 0) {
        receive((Tid tid) { tidsRemaining--; });
    }
}

I'm hoping we might see some interesting languages or toolkits crawl out of the woodworks, so come on Ars, do your worst!
And of course, if one of you smart folks has an idea for a more interesting challenge, throw that out there as well.
 
Not actually tested, so it probably has some errors.
Code:
unsigned int* sleep_sort(unsigned int* numbers, size_t count) {
	dispatch_queue_t q = dispatch_queue_create("lol", NULL);
	unsigned int* result = calloc(count, sizeof(unsigned int));
	size_t offset = 0;
	
	dispatch_suspend(q);
	dispatch_apply(count, dispatch_get_global_queue(0, 0) ^(size_t i) {
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, numbers[i] * NSEC_PER_SEC), q, ^{
			size_t my_offset = dispatch_atomic_inc(&offset);
			result[my_offset - 1] = numbers[i];
		});
	});
	dispatch_resume(q);
	dispatch_sync(q, ^{});
	dispatch_release(q);
	memcpy(numbers, result, sizeof(unsigned int) * count);
	free(result);
	return numbers;
}
 

pyu

Ars Praefectus
5,108
Subscriptor
Code:
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Sorter {

	public <T extends Number> List<T> sleepSort(List<T> values)
			throws InterruptedException {
		return sort(values, TimeUnit.MILLISECONDS, 10);
	}

	private <T extends Number> List<T> sort(List<T> values,
			final TimeUnit timeUnit, final long multiplier)
			throws InterruptedException {
		final List<T> result = new CopyOnWriteArrayList<T>();
		final CountDownLatch startSignal = new CountDownLatch(1);
		final CountDownLatch endSignal = new CountDownLatch(values.size());
		ExecutorService pool = Executors.newFixedThreadPool(values.size());
		try {
			for (final T value : values) {
				pool.submit(new Callable<Void>() {
					public Void call() throws InterruptedException {
						startSignal.await();
						timeUnit.sleep(value.longValue() * multiplier);
						result.add(value);
						endSignal.countDown();
						return null;
					}
				});
			}
			startSignal.countDown();
			endSignal.await();
			return result;
		} finally {
			pool.shutdown();
		}
	}
}

There should be other ways to write it in Java, since java.util.concurrent is awesome and is deserving of praise. :) The multiplier is there just in case if the JVM bug related to sleep is still there [never bothered to go back to check if they fixed it].
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[] { 7,5,2,1,3,4,8,9,6 };

numbers
.AsParallel()
.WithDegreeOfParallelism(numbers.Length)
.ForAll(x =>
{
Thread.Sleep(x * 10);
Console.WriteLine(x);
});
}
}
}
 
Forgot to preview... sorry.

Note that this example will blow up when you pass more than 63 values through it.


Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[] { 7,5,2,1,3,4,8,9,6 };

            numbers
                .AsParallel()
                .WithDegreeOfParallelism(numbers.Length)
                .ForAll(x =>
                    {
                        Thread.Sleep(x * 10);
                        Console.WriteLine(x);
                    });

            Console.ReadLine();
        }
    }
}
 
Bhelyer":3ppeevs1 said:
Note that this example will blow up when you pass more than 63 values through it.

Why?

Its an underlying Windows NT kernel limitation; if you must have more than 64 threads you need to supply your own notification mechanism.

However for almost any mundane parallel task PLINQ is more than sufficient, and the time saved by letting the API handle your threading and synchronization far outweighs the several % benefit you would see by spawning more threads.
 
pyu":1s9huh94 said:
Bhelyer":1s9huh94 said:
The use of code blocks and indentation would make that nifty example more readable, Ravensroke. :)

pyu, how old is java.util.concurrent?

Hmm. No idea. The latest contributions appeared in Java 1.5... so, around four/five years ago? :confused:
Actually, it started in 1.5, it got updated in 1.6, and it'll get updated again in the next release.
 

Horatio

Ars Legatus Legionis
24,430
Moderator
RX:
Code:
namespace SleepSort
{
    using System;
    using System.Reactive.Linq;

    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[] { 7, 5, 2, 1, 3, 4, 8, 9, 6 };

            var sortedObservable = numbers.ToObservable().SelectMany(n => Observable.Return(n).Delay(TimeSpan.FromSeconds(n)));

            sortedObservable.Subscribe(i => Console.Write("{0} ", i));
            Console.ReadKey();
        }
    }
}
 

xspartachris

Ars Scholae Palatinae
1,175
DrPizza":xlsgas8b said:
Not actually tested, so it probably has some errors.
Code:
unsigned int* sleep_sort(unsigned int* numbers, size_t count) {
	dispatch_queue_t q = dispatch_queue_create("lol", NULL);
	unsigned int* result = calloc(count, sizeof(unsigned int));
	size_t offset = 0;
	
	dispatch_suspend(q);
	dispatch_apply(count, dispatch_get_global_queue(0, 0) ^(size_t i) {
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, numbers[i] * NSEC_PER_SEC), q, ^{
			size_t my_offset = dispatch_atomic_inc(&offset);
			result[my_offset - 1] = numbers[i];
		});
	});
	dispatch_resume(q);
	dispatch_sync(q, ^{});
	dispatch_release(q);
	memcpy(numbers, result, sizeof(unsigned int) * count);
	free(result);
	return numbers;
}

Dispatch groups are also a great way to express this sort of problem:

Code:
+ (NSArray*)sortedArrayFromArray:(NSArray*)array {
	NSMutableArray* sortedArray = [NSMutableArray array];
	dispatch_group_t sleepGroup  = dispatch_group_create();
	for (NSNumber* num in array) {
		dispatch_group_async(sleepGroup, dispatch_get_global_queue(0, 0), ^(void) {
			sleep([num unsignedIntValue]);
			@synchronized(sortedArray) {
				[sortedArray addObject:num];
			}
		});
	}
	dispatch_group_wait(sleepGroup, DISPATCH_TIME_FOREVER);
	dispatch_release(sleepGroup);
	return sortedArray;
}

… but the whole problem is a race (that is only avoided because the sleep is so long), since you can't make assumptions about the relative start times of blocks submitted to concurrent queues (and thread pools in general).

EDIT: Forgot to release the sleepGroup. Oops.
 

hd580

Wise, Aged Ars Veteran
111
Ravensroke":3gfx1i3l said:
Code:
...
            int[] numbers = new int[] { 7,5,2,1,3,4,8,9,6 };

            numbers
                .AsParallel()
                .WithDegreeOfParallelism(numbers.Length)
                .ForAll(x =>
                    {
                        Thread.Sleep(x * 10);
                        Console.WriteLine(x);
                    });
...

Hm, didn't sort for me at (x * 10). It improved incrementally up to (x * 5000) where it finally returned the correct order. Intel T7250 2-core CPU.
 

S. Carton

Ars Scholae Palatinae
937
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>
 

fitten

Ars Legatus Legionis
55,634
Subscriptor++
Yeah, the whole thing is a race condition. It depends on how your queue works and such.
Here's a very quick and dirty one using base Threads. It'll wait now.

Code:
using System;
using System.Linq;
using System.Threading;

namespace SleepSort
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 7, 5, 2, 1, 3, 4, 8, 9, 6 };
            SemaphoreSlim sem = new SemaphoreSlim(0, numbers.Length);
            numbers.ToList<int>().ForEach(i => new Thread((o) =>
            {
                Thread.Sleep(i * 1000);
                Console.WriteLine(i);
                sem.Release();
            }).Start());
            foreach (int i in Enumerable.Range(0, numbers.Length))
                sem.Wait();
            Console.WriteLine("Done. Press any key to exit.");
            Console.ReadKey();
        }
    }
}

To test, you should use the worst case data set:

int[] numbers = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };

That should expose queuing issues ;)
 
.Net 4.5 + C#5

Code:
using System;
using System.Threading.Tasks;

class C {
  void SleepSort(IEnumerable<int> input) {
    foreach (var i in input) {
      Task.Delay(TimeSpan.FromSeconds(i)).ContinueWith(_ => Console.WriteLine(i));
    }
  }
}

Gets much simpler in a later version of C#. But alas, i can't show that yet.

Also, the above is a version that is allowed to return before all the functions are printed. If you need to wait on the values, that's fairly easy to do as well.
 

FogleBird

Ars Tribunus Militum
2,237
Here's a Python version that actually returns a sorted list instead of just printing the results to stdout. So you can use it like a real sort function!
Code:
import time
import multiprocessing

def helper(queue, value):
    time.sleep(value)
    queue.put(value)

def sleep_sort(values):
    queue = multiprocessing.Queue()
    for value in values:
        multiprocessing.Process(target=helper, args=(queue, value)).start()
    result = [queue.get() for i in range(len(values))]
    return result

if __name__ == '__main__':
    numbers = [1, 9, 2, 8, 3, 7, 4, 6, 5]
    numbers = sleep_sort(numbers)
    print numbers
 
… but the whole problem is a race (that is only avoided because the sleep is so long), since you can't make assumptions about the relative start times of blocks submitted to concurrent queues (and thread pools in general).

EDIT: Forgot to release the sleepGroup. Oops.
Yeah using group is a nice way to wait for it to all finish, but I didn't want to have an arbitrary number of sleeping threads. This means not using dispatch_group_async; I'd have to use the same dispatch_after as I'm using now (which uses timers), and join/leave the group manually.

It's a little odd there's no explicit barrier API for serial queues--it seems to me that that would be quite handy. Even more handy would be a barrier API for parallel queues, as there's no easy or effective way to implement one by hand.
 
Is mine the only C++ entry? Open MP seems to ignore thread counts beyond 63, but it sorted the first 63 items of my 100 number test perfectly.

Code:
#include <cstdlib>
#include <iostream>
#include <string>
#include "windows.h"
#include "omp.h"


int main(int argc, char* argv[])
{
#pragma omp parallel num_threads(argc-1)
	{
		int i = omp_get_thread_num();
		int n = std::atoi( argv[ i ] );
		std::string output( argv[ i ] );
		output += "\n";
		Sleep( n );
		std::cout << output;
		std::cout.flush();
	}
	return 0;
}
 

Ardax

Ars Legatus Legionis
19,794
Subscriptor
Metasyntactic":29y33soc said:
Also, for people spawning threads, try your program out with an input of a few thousand. You may get some interesting results depending on if you're running on several of the common OSs/platforms out there.
Won't the Windows version crash and burn quickly unless you reduced the default stack size? (Or compiled as an x64 binary... :scared: )
 

fitten

Ars Legatus Legionis
55,634
Subscriptor++
Ardax":gwsvogz9 said:
Metasyntactic":gwsvogz9 said:
Also, for people spawning threads, try your program out with an input of a few thousand. You may get some interesting results depending on if you're running on several of the common OSs/platforms out there.
Won't the Windows version crash and burn quickly unless you reduced the default stack size? (Or compiled as an x64 binary... :scared: )

Any platform will eventually run out of some resource if you have too many threads, but even 500+ threads are no problem at all on my Windows box (just ran my app with 10,000 integers and it was steady at 500 threads or so). The problem is that once you grab up all the 'easy' threads, it starts taking time and you won't sort properly. That 1 at the end of the 10,000 array may not even start running by the time the first 9 in your array has completed.
 

MilleniX

Ars Tribunus Angusticlavius
8,139
Subscriptor++
BitPoet":yytuj4dn said:
Wonder what an MPI version of this would look like...

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

Code:
#include <mpi.h>
#include <unistd.h>

int main(int argc, char **argv)
{
  int size, rank, v;
  MPI_Init(&argc, &argv);

  MPI_Comm_size(MPI_COMM_WORLD, &size);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);

  if (size != argc)
    MPI_Abort();

  if (rank == 0) {
    for (int i = 0; i < argc; i++) {
      MPI_Recv(&v, sizeof(int), 1, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD);
      printf("%d ", v);
    }
    printf("\n");
  } else {
    v = atoi(argv[rank]);
    sleep(v);
    MPI_Send(&v, sizeof(int), 1, 0, 0, MPI_COMM_WORLD);
  }

  MPI_Finalize();
  return 0;
}

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

Phil
 
Status
Not open for further replies.