Proper way to code multithreaded applications?

Regan Heath regan at netmail.co.nz
Fri Jun 1 07:31:29 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)

Yep *shrug* those are perhaps bad method names.

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

No, it's intended for when you want to wait for another thread to finish.  You can't wait for yourself to finish because as long as you wait you're not finished.

> * yield has no specific timing constraints

No.. it just calls Sleep(0); (on windows).

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

You're probably going to have to synchronize it yourself with a mutex or similar.

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

Have you heard of nanosleep?

> 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.

I reckon you write an msleep implementation which calls Sleep, msleep, usleep or nanosleep (depending on the platform) and call that.

Regan Heath


More information about the Digitalmars-d-learn mailing list