Some problems writing a threaded program

Simon Marlow simonmarhaskell at gmail.com
Mon Feb 11 06:39:24 EST 2008


John Vogel wrote:
> I am running my program in WinXP with ghc 2.6.8
> 
> If you install netstat and change the parameters it should still work in 
> linux.
> 
> 
> Why does thread # 3 dominate over the over threads int the output?
> Why does thread # 4 never seem to run?
> 
> I can't use the sleep function in System.Process.Win32 since it puts all 
> the
> threads asleep at the same time.  Is there a way to put only one thread 
> asleep?
> 
> That would allow more of a chance for thread #4 to run.

I haven't looked in detail at what happens in your program, but there is a 
matter of style here: you appear to be using busy-waiting and polling a 
lot.  GHC's runtime shouldn't be considered "fair" in any sense other than 
the most basic: a thread will get to run eventually, but if it immediately 
blocks then it loses its timeslice.  There's no guarantee that a thread 
will get a fair share of the CPU.

So busy-waiting and polling will often suffer from a lack of fairness in 
the scheduler.  Let me be a little more concrete: you're doing a lot of 
output to stdout.  Now, stdout has a lock on it - only one thread can be 
holding stdout at any one time.  Often, a thread will be preempted while 
holding the stdout lock, and since the other threads are all waiting to 
output to stdout too, none of them can make progress, so the original 
thread gets another timeslice (unfair!).  This is why, if you try to write 
one of those AAAABBBB... concurrency tests using GHC, you'll probably get 
AAAAAAAAAA...

GHC's scheduler is intentionally simple, because it is designed to cope 
with workloads that consist of mostly *blocked* threads, and a very few 
running threads.  However, you might get more fairness using a couple of 
cores and running with +RTS -N2.

Perhaps one day we'll have to consider questions of fairness and priority, 
hopefully in the context of a user-programmable scheduler.  But for now, 
this is the way it is.

Cheers,
	Simon


More information about the Glasgow-haskell-users mailing list