thread-ring benchmark

bearophile bearophileHUGS at lycos.com
Thu Dec 20 12:50:46 PST 2007


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