View previous topic :: View next topic |
Author |
Message |
teales
Joined: 21 May 2007 Posts: 24 Location: Bangalore
|
Posted: Mon May 21, 2007 9:43 am Post subject: Threads, delegates, and all that. |
|
|
I did not find the threads documentation too helpful, so I played with them, and the following is the outcome.
Code: |
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);
}
|
Hope this is helpful. |
|
Back to top |
|
|
teales
Joined: 21 May 2007 Posts: 24 Location: Bangalore
|
Posted: Tue May 22, 2007 1:32 am Post subject: |
|
|
I was overzealous in tidying up the code before I posted it.
To make it compile you'll need
import std.c.time; |
|
Back to top |
|
|
jcc7
Joined: 22 Feb 2004 Posts: 657 Location: Muskogee, OK, USA
|
Posted: Tue May 22, 2007 2:37 pm Post subject: |
|
|
Cool! I added your example to the wiki as: Threads and Delegates Example. Thanks for your contribution. |
|
Back to top |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|