开发者

Why do my Perl threads execute randomly on the first run but in order on subsequent runs?

开发者 https://www.devze.com 2022-12-20 19:58 出处:网络
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 inte

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 eac开发者_开发知识库h 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消