Multi-threaded programs have multiple execution points, i.e. different parts of the code may be executed at the same time.
Creating threads
Every multi-threaded program should include:
use threads;
#New threads are created using:
threads->new(\&thread_sub, @sub_params)
#which returns the thread object.
use threads;
$thr1 = threads->new(sub { ... code 1 ... });
$thr2 = threads->new(sub { ... code 2 ... }, $param1, $param2);
create() is a synonym for new().
Thread control methods
One thread may explicitely give up CPU to other threads using: threads->yield;
The thread that created another thread may wait for the child (this operation is blocking unless the child thread is already finished):
$child_thread->join;
#Any data that the thread subroutine returns
#may be accessed in the parent thread
use threads;
my $child_thread = threads->new(\&my_function);
# ...
my @returned_data = $child_thread->join;
print "Child thread returned @returned_data";
sub my_function
{
return "Inside Thread", 2007, "Perl Threads", 12;
}
#The parent thread may also officially
#stop to worry about the child using:
$child_thread->detach;
More thread control methods Getting the object for thread currently running:
my $this_thread = threads->self;
#Getting the list of objects for all running and
#not detached threads:
my @threads = threads->list;
#Getting the thread id (the main thread has tid=0):
my $tid = $thread->tid;
#Comparing thread objects:
foreach (threads->list) { print $_->tid, "\n"
unless threads::equal($_, threads->self); }