Perl threads are a big and rather cludgy hammer, and should only be used when you need to share lots of data between many processes. They're great to have when you truly need them, but in your case, you don't truly need them. :)

Since you know exactly how long you want to wait, you can simply use the alarm function. You've got high precision for your timing, so you should probably use the Time::HiRes module, which is almost certainly a core module for you. To get all of this to work, a skeleton of your code might look like this:

use Time::HiRes qw(alarm); # Pre-declare any variables you'll need in play_func and in # the main code my %all_files; sub play_func { ## Most of your originally posted code goes here, but ## replace the call to sleep with this: alarm ($song_length); } # You'll need to associate the alarm signal handler with # play_func like so: $SIG{ALRM} = \&play_func; # Initialize your data here, such as your playlist # Kick-off the play loop by calling play_func once: play_func(); # Put your own looping/interface code here: while(1) { # This will loop until you call 'last;' or exit. # When the alarm signal goes off, Perl will jump to # your alarm-handling code and execute that, then # return to whatever it was doing in here. # This will lead to a slight interrupt in this loop, # but it probably won't be noticeable. }

Hope that's a useful alternative approach!


In reply to Consider using alarms instead of threads by pdltiger
in thread Looping in the background of your main program by Baphi

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.