views:

63

answers:

2

In the course of testing the code for the question How can I store per-thread state between calls in Perl? I noticed that the first I time execute the script the threads execution are fairly well interleaved with each other. But on all subsequent executions of the script all the threads run almost perfectly in the order of their creation with very little interleaving. This is Perl ithreads on Ubunutu 9.04.

Maybe someone could enlighten me about what's going on?

+3  A: 

Thread scheduling is a complex implementation detail of the OS. Trying to figure out how it works by observing how threads are scheduled is next to impossible. And you shouldn't really make any assumptions based on these observations. On different hardware the OS may schedule the threads differently.

Brian Rasmussen
Obviously I'm not depending on this, it just seemed odd and I'm curious if anyone has a reasonable theory.
Robert S. Barnes
@Robert: I am sorry, I didn't mean to imply that your code depended on the scheduling.
Brian Rasmussen
@Brian: No problem. What's interesting is that Zaid tested it on Win7 and it exhibited the exact same behaviour as on Ubuntu. Maybe it has something to do with Perl itself?
Robert S. Barnes
+3  A: 

Your threads are running in creation order largely due to implementation details in Perl and the operating system (mainly because their individual execution time is below the operating system's shortest execution-time slice). To interleave the threads, you can use sleep rather than yield (or make the threads do some real work).

Keep in mind that yield in Perl threads is just a suggestion, which is unlike the way yield works in some other languages. Since Perl threads are concurrent and are largely managed by the operating system's scheduler, unless you use some sort of mutex to block execution, its not really possible to predict their execution order.

Eric Strom
Yeah, I added a loop of 100 multiplies and divides in the foo function and that caused consistent interleaving of the threads.
Robert S. Barnes