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










June 9th, 2007 at 6:37 am
By the way, the documentation of class thread is here.
June 9th, 2007 at 7:40 pm
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