Multithreaded programming in D
Friday, June 8th, 2007While 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

