in reply to Re: Dormus interruptus
in thread Dormus interruptus

Thank you - that gets the delay down considerably. Would it be of value to avoid the time() call completely?

for (1..5) { sleep 1; return if $quit; }

Replies are listed 'Best First'.
Re^3: Dormus interruptus
by BrowserUk (Patriarch) on Jun 25, 2004 at 19:42 UTC

    That will probably work just fine.

    The downside is that it gives a greater margin for error with respect to the timing of the loop whilst it is running.

    Using sleep 1; doesn't guarentee that your code will wake up after exactly 1 second. It guarentees that your code will wake up the next time your thread gets scheduled after one second has elapsed. The difference is subtle, but it generally means that the delay will be longer than 1 second.

    Using a counting loop means that the overall error will be the accumulation of all the errors from the 5 (in this example) calls to sleep.

    Using time to control the loop, if the accumulated errors after 4 sleeps are such that the total time slept is greater than 5 seconds, then the loop will terminate and avoid the extra delay.

    For most applications this will make very little difference, but if (for example) the thread was accumulating and presenting statistics, like average processor usage or network throughput, then the difference between sleeping for "5 and a bit seconds" or "5 x 1 and a bit seconds" could becomes significant.

    A word of caution regarding signals. If your application can be switched to a fork implementation, then they are probably the way to go. However, your OP mentions a "global shared hash" which makes threads the obvious choice.

    Historically, threads and signals do not play well together. At the OS level, signals are a "per process" concept, meaning that a signal issued by one thread will tend to affect (and possibly terminate) all threads.

    They are also enacted at the machine code level. Each of perls opcodes are made up of at leasts 10s of machine -level opcodes, and sometimes 1000s. That means that when the interuption occurs, it can happen at any point in the processing of a single perl opcode (half way through a sort for instance), and that can lead to bizzare consequences.

    (Read the pod for Thread::Signal and "safe signals" for some more info).

    Thread::Signal was intended to 'fix' the problems with signals and threads, but that was for pthreads rather than iThreads. I am not sure how 5.8.x "safe-signals" interact with threads as in essence, signals don't work on win32. They may be perfectly complete under *nix and iThreads, but it would be worth your time doing a little research if you are considering them.


    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, algoritm, algorithm on the code side." - tachyon