The one reason i wouldn't use it is because it's limited to 1 second granuality. But i'm one of those damned perfectionist. As for the API, since 5.8.0 there is one way to do it - nothing shared, and I don't like my threads like that. So i don't remember what it's like, but that's a good reason not to use them in the example.
For the record, the main reason I commented was in the hopes that you add a
sleep 1 while $count; # Or use Thread::Semaphore
so that people who don't know about threads wouldn't think that's the only way. I guess I should have been more polite or something... =)
| [reply] [d/l] |
You were perfectly polite. Sorry that I gave the impression otherwise. My answer was my best reasoning for doing things the way I do.
When you said "semaphores", I assumed you were talking about the threads::shared cond_* apis rather than Thread::Semaphore as the latter is used for serialising access to shared resources rather than signalling. I don't see how you would have a parent thread wait for the termination of it's children using that? If you know, please educate me.
I have used the threads::shared cond_* apis for this purpose in the past but those apis don't seem ideally suited to this purpose either. So far, I have rarely needed their complexity.
I should probably have used lock on $count in my example, but on my single cpu box I have never managed to detect anything that indicated they were necessary for increment and decrements.
Ideally, I should be able to use threads->list to wait for the count of running threads to drop to zero, but it only reports on undetached threads. Which would have worked in this case as I didn't detach the asyncs, but that was an oversight. I normally do.
As for the granularity. I normally use Win32::Sleep for this purpose, as it has millisecond capability, but that's obviously platform specific. I just switched it to sleep cos it's universal.
You could also use select undef, undef, undef, .1 while $count; to reduce the granularity if time is critical. In this case the program was only going to print the results and terminate, so at best, the user might see the first result 0.9 of a second earlier.
Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
| [reply] [d/l] |