Proper way to code multithreaded applications?

Sean Kelly sean at f4.ca
Fri Jun 1 10:04:37 PDT 2007


Jason House wrote:
> I've started writing a multithreaded application and I'm slowly hitting 
> into different annoyances.  I'm curious if anyone knows the proper way 
> to handle some of these issues.
> 
> * must call start to run a thread but thread execution starts with run 
> (If that confuses, which it was intended to do.  Make your own run 
> method for what you want the thread to do but call the start function 
> when you want the thread to begin)

Well, it's an implementation issue that start() must basically call 
run() in the new thread.  What I decided to do in Tango to lessen the 
confusion is to always have the user pass the method to run to the 
superclass if inheriting from Thread:

     class MyClass : Thread
     {
         this()
         {
             super( &run );
         }

         void run()
         {
             ...
         }
     }

> * wait can't be used inside a thread to wait for itself

The purpose of this method is to wait for the thread to complete, so if 
a thread could wait on itself the thread would effectively deadlock.  In 
Tango this method is called join(), which is more consistent with 
popular terminology.

> * yield has no specific timing constraints

It shouldn't.  yield() is simply intended to yield the current thread's 
timeslice to another thread.  On Win32, this is done via Sleep(0) or 
Sleep(1) (depending on how nice you want to be), and on Posix this is 
pthread_yield().

> * derr is not synchronized.  Debug output from different threads can get 
> multiplexed together.

In my opinion, this is the correct choice from a performance standpoint.

> * msleep isn't available on all platforms (problem inherited from C)
> * usleep isn't thread safe (problem inherited from C)

This is only an issue because Phobos threads lack a sleep() routine. 
Tango threads do not.  And to reply to Regan as well, nanosleep isn't 
available everywhere either :-)  The most commonly implemented methods 
are sleep() and usleep() in <unistd.h>.  In fact, I think these may 
actually be required (nanosleep is a part of the realtime extensions IIRC).

> My big issue at the moment is how to cause a thread to delay 
> (approximately) for a period of time that I specify.  I guess I might be 
> ok with yield when the application is in full swing, but I really hate 
> for nearly idle threads to peg the CPU when there's nothing to do.

You want sleep(), usleep(), or nanosleep() for Posix, and Sleep() or 
SleepEx() for Win32.


Sean


More information about the Digitalmars-d-learn mailing list