thread-ring benchmark
Alan Knowles
alan at akbkhome.com
Thu Dec 20 15:59:45 PST 2007
try googling for "thread-limit.c proc"
There are a few /proc settings that enable more threads to be run,
(basically you are running out of resources, and Phobos is hiding the
real error - you need the error return from thread_start.)
I have got it up to quite a high number of threads.
However !!IMPORTANT!! - this is a horrible example on how to use
threads, and for beginners it will confuse them horribly.
If you do make this code public anywhere, please put a note in it
"NEVER USE THREADS LIKE THIS!" - threads are intended to be used in
pools, and re-used, if you write your application like this, it will
ALWAYS crash eventually, whatever you do...
(As you may have guessed - I got caught by that one...)
Regards
Alan
bearophile wrote:
> This is the D thread-ring benchmark on the Shootout site:
> http://shootout.alioth.debian.org/gp4/benchmark.php?test=threadring&lang=dlang&id=0
>
> For me on DMD 1.024 on Win it works, but it doesn't work on the site (it gives: Error: Thread error: failed to start), maybe it's a thread problem on Linux, so it may be a Phobos bug.
>
> This is my shortened & simplified version, it uses a static array local to the main() (indent reduced to just 2 spaces):
>
> // The Computer Language Benchmarks Game
> // http://shootout.alioth.debian.org/
> // contributed by Alexander Suhoverhov
> // Modified by bearophile
>
> import std.thread: Thread;
> import std.conv: toInt;
>
> int n;
> bool finished = false;
>
> class MessageThread: Thread {
> MessageThread next;
> int message, name;
>
> int run() {
> while (true) {
> while (!message && !finished)
> yield;
>
> if (finished)
> return 0;
>
> if (message == n) {
> finished = true;
> printf("%d\n", name);
> return 0;
> }
>
> next.message = this.message + 1;
> this.message = 0;
> }
> return 0;
> }
> }
>
> void main(char[][] args) {
> const NUM_THREADS = 503;
> MessageThread[NUM_THREADS] ring;
>
> n = args.length == 2 ? toInt(args[1]) : 100_000;
>
> foreach(i, ref mt; ring)
> mt = new MessageThread;
>
> foreach(i, mt; ring) {
> mt.name = i + 1;
> mt.next = ring[(i + 1) % ring.length];
> mt.start;
> }
>
> ring[0].message = 1;
>
> foreach(mt; ring)
> mt.wait;
> }
>
>
> The good thing is that it on my PC it runs faster than the Java6 version (the given n is 10 millions).
> The bad thing is that it doesn't print 361 (but probably one less, 360), so if you spot the problem you can suggest it.
> Note that the Java version doesn't use global variables like n and finished. There is a simple way to avoid the need of finished, using std.c.stdlib.exit, but the code requires more time to run.
> Note that the Haskell version (that uses light threads) works in about 1/10 of the time... (The Erlang/Oz versions too are fast) so maybe the D threading of Phobos may become quite faster in the future, using similar "threads".
>
> Bye,
> bearophile
More information about the Digitalmars-d-learn
mailing list