Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What else can i do 'sleep' when the sleep() can't work well with alarm?

Tags:

sleep

perl

alarm

There are many documents say "you should avoid using sleep with alarm, since many systems use alarm for the sleep implementation". And actually, I'm suffering with this problem. So does anyone can help me that what else i can do 'sleep' when the sleep() can't work well with alarm? I have already tried 'usleep' of the Time::HiRes module, and select() function. But they didn't work either.

like image 634
William.Zhou Avatar asked Jul 28 '11 08:07

William.Zhou


People also ask

What to do when you cant sleep and have work?

Take a bath, color, write in a journal, paint, listen to soothing music, read, stretch, or do a puzzle. Putting aside stressful and worrying thoughts until bedtime can make it difficult for you to fall asleep, and these thoughts might wake you up in the middle of the night.


2 Answers

Seeing as you're being interrupted by alarms, and so can't reliably use sleep() or select(), I suggest using Time::HiRes::gettimeofday in combination with select().

Here's some code that I've not tested. It should resist being interrupted by signals, and will sleep for the desired number of seconds plus up to 0.1 seconds. If you're willing to burn more CPU cycles doing nothing productive, you can make the resolution much better:

...
alarm_resistant_sleep(5); # sleep for 5 seconds, no matter what
...

use Time::HiRes;

sub alarm_resistant_sleep {
  my $end = Time::HiRes::time() + shift();
  for (;;) {
    my $delta = $end - Time::HiRes::time();
    last if $delta <= 0;
    select(undef, undef, undef, $delta);
  }
}
like image 178
DrHyde Avatar answered Sep 24 '22 03:09

DrHyde


You can try AnyEvent:

use AnyEvent;

my $cv = AnyEvent->condvar;
my $wait_one_and_a_half_seconds = AnyEvent->timer(
    after => 1.5,
    cb => sub { $cv->send }
);     
# now wait till our time has come
$cv->recv;
like image 40
Eugene Yarmash Avatar answered Sep 23 '22 03:09

Eugene Yarmash