Add this blog to Del.icio.us, Digg or Furl | Create Watchlist for this blog

Multithreaded programming in D

While in C++ there was no build-in threading support, D comes with a JAVA-like class “Thread”. So while in C/C++ you had to mingle around with threading libs like pthread or solaris-threads, in D you can leave that problem to phobos.

A simple example shows all the simplicity:

import std.c.time;
import std.stdio;
import std.thread;

int runThread(void *ptr)
{
  printf("Thread %d startedn", cast(int)ptr);
  sleep(10);
  printf("Thread %d endedn", cast(int)ptr);
  return 0;
}

int main()
{
  Thread t1 = new Thread(&runThread, cast(void *)1);
  t1.start();
  sleep(2);
  Thread t2 = new Thread(&runThread, cast(void *)2);
  t2.start();

  while ((t1.getState() == std.thread.Thread.TS.RUNNING)
            || (t2.getState() == std.thread.Thread.TS.RUNNING))
    Thread.yield ();   

  printf("program readyn");
  return 0;
}

That’s it. Save the code as ThreadTest.d, than compile with “gdc ThreadTest.d” and run a.out (or a.exe). What you get as output should be very similar to:

rainer@ThinkTop ~
$ ./a.exe
Thread 1 started
Thread 2 started
Thread 1 ended
Thread 2 ended
program ready

Social Bookmarking:
Add to social bookmarking sites.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • MisterWong
  • Furl
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati

And I've started a Drupal relaunch of my EDV Beratung now.

2 Responses to “Multithreaded programming in D”

  1. Rainer Says:

    By the way, the documentation of class thread is here.

  2. Rainer Says:

    BTW2: Concerning mutexes:

    There is no such thing like pthread_mutex in D, but D has basic critical section support built in the language by using the “synchronized” statement (like JAVA) or attribute modifier. It doesn’t have wait/notify or other types of locks.

    There is no support for more sophisticated mutexing. But I think there are some classlibs already :-)

Leave a Reply

I appreciate all comments that add substantial content to my articles. I do not like "link-building" comments and I do not like "congratulation" comments. Every such like data posted here will go to akismet hell.