If the worker does not share data with the main program, it is probably best to fork it off as a child process.

Threads are expected to behave nice, as they can write shared data, terminate the whole process with an exec, etc. Implementing the blocking/timeout logic in a thread itself should be preferable. In any case, threads i.e. clones share signal dispositions (signal handlers), so extra care should be taken when mixing threads and signals.1 (Don't use alarm.)

That said, you can work around the problem by using Thread::Queue and a baby-sitter.

#! /usr/bin/perl use strict; use warnings; use Data::Dumper; use threads; use Thread::Queue; my $Q = Thread::Queue->new(); sub manage { async{ $Q->enqueue({ $_->tid => $_->join }) }->detach for @_ } sub worker { print "Worker started.\n"; # 1 while 1; return 42; } manage( threads->create(\&worker) ); print Dumper $_ for $Q->dequeue_timed(2);

1) Update. Perl will dispatch signals, thus threads can have their separate handlers. But not a mix of 'IGNORE'/'DEFAULT'/code. It also appears that most signals are blocked in threads; to get around this, one might use POSIX::sigprocmask. But it's hopeless anyway: alarm is per-process.
Correction: Just blocking the ALRM in main thread (after thread creation) allows another thread to catch it. I don't know if this can be relied on...


In reply to Re: Why does threads::join block SIGALRM by oiskuu
in thread Why does threads::join block SIGALRM by CDahn

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.