use File::Slurp; use String::Diff; use threads; use threads::shared; use Thread::Queue; my $thread_limit = 15; my $worker = Thread::Queue->new(); # Worker Threads my $result = Thread::Queue->new(); # Result Threads my @pool = map { threads->create(sub { my $tid = threads->tid; my ($worker, $result) = @_; while( my $item = $worker->dequeue ) { // code that I have that might die unexpectedly, or // hang for a long time // Some Example code here: my $old_text = 'something I got from text version 1'; my $new_text = 'something I got from text version 2'; %String::Diff::DEFAULT_MARKS = (remove_open => '', remove_close => '', append_open => '', append_close => ''); my ($old_diff, $new_diff) = String::Diff::diff($old_text, $new_text); my $diff = "\n\n\n"; $diff .= "\n\n\n"; $diff .= "

New Version

\n

$new_diff

\n

Old Version

\n

$old_diff

\n"; $diff .= "\n\n"; write_file("filename.html", {binmode => ':utf8'}, $diff); // More code ... $result->enqueue($tid); } $result->enqueue(undef); }, $worker, $result); } 1 .. $thread_limit; # Queue up all work items (Say, I have 10000 texts to compare) $worker->enqueue($_) for (0 .. 10000); # Tell all workers there are no work items $worker->enqueue((undef) x $thread_limit); # Process the results for ( 1 .. $thread_limit) { while (my $tid = $result->dequeue()) { // Can I handle terminated threads or // time out threads here? // If so, how? } } # Clean up the threads $_->join() for @pool;