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):
But of course, I had to take a crack at it myself: (In D)
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.
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.
)