Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Threads and Delegates

Part of Standard Library Category

Example

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

class Foo
{
   int _v;

   this(int n)
   {
      _v = n;
   }

   public int glob()
   {
      return _v;
   }
}

class WorkerThread
{
   int _v;

   this(int n)
   {
      _v = n;
   }

   // Here's a private member function - we'll call this from the run() method
   void identify()
   {
      writefln("WorkerThread(%d)", _v);
   }

   // When run is called via the delegate it will have the appropriate this
   // pointer, and so has access to all the fields and methods of its class.
   public int run()
   {
      for (;;)
      {
         sleep(2);
         identify();
      }
      return 0;
   }
}

// In the thread 2 case, we override the thread class, and provide the run method
// explicitly
class Thread2 : Thread
{
   int _v;

   this(int n)
   {
      _v = n;
   }
   public int run()
   {
      for (;;)
      {
         sleep(2);
         writefln("Thread2 %d", _v);;
      }
      return 0;
   }
}

void bar(int delegate() a)
{
   writefln("rv = %d", a());
}

// In the case of thread 3, this will serve as the run method, and
// it will be called with the value of the second argument to the
// thread constructor (the documentation is not correct in this respect).
int x(void *p)
{
   int *ip = cast(int*) p;
   for (;;)
   {
      sleep(2);
      writefln("Thread3 %d", *ip);
   }
   return 0;
}


void main(char[][] args)
{
   // Before we get to threads, these first few lines just illustrate the
   // general ideas of delegates as applied to class member functions.
   Foo foo = new Foo(42);
   int delegate() dg = &foo.glob;
   int n = dg();
   writefln("n = %d", n);
   bar(dg);
   int n3 = 123;

   // Now the different ways of instantiating threads.
   WorkerThread wt = new WorkerThread(22);
   dg = &wt.run;
   Thread t1 = new Thread(dg);
   t1.start();

   Thread2 t2 = new Thread2(321);
   t2.start();

   Thread t3 = new Thread(&x, &n3);
   t3.start();

   sleep(10);
} 

Sample Batch File

@echo off
set pgm=ThreadsAndDelegatesExample
dmd %pgm%.d 
%pgm%.exe

pause
erase *.obj
erase *.map

Tested Environment

Tested with Digital Mars D Compiler v1.014 on Windows 2000.

Source

Based on "Threads, delegates, and all that" by teales.