threads - Perl interpreter-based threads
This document describes threads version 2.42
The "interpreter-based threads" provided by Perl are not the fast, lightweight system for multitasking that one might expect or hope for. Threads are implemented in a way that makes them easy to misuse. Few people know how to use them correctly or will be able to provide help.
The use of interpreter-based threads in perl is officially discouraged.
use threads ('yield',
'stack_size' => 64*4096,
'exit' => 'threads_only',
'stringify');
sub start_thread {
my @args = @_;
print('Thread started: ', join(' ', @args), "\n");
}
my $thr = threads->create('start_thread', 'argument');
$thr->join();
threads->create(sub { print("I am a thread\n"); })->join();
my $thr2 = async { foreach (@files) { ... } };
$thr2->join();
if (my $err = $thr2->error()) {
warn("Thread error: $err\n");
}
# Invoke thread in list context (implicit) so it can return a list
my ($thr) = threads->create(sub { return (qw/a b c/); });
# or specify list context explicitly
my $thr = threads->create({'context' => 'list'},
sub { return (qw/a b c/); });
my @results = $thr->join();
$thr->detach();
# Get a thread's object
$thr = threads->self();
$thr = threads->object($tid);
# Get a thread's ID
$tid = threads->tid();
$tid = $thr->tid();
$tid = "$thr";
# Give other threads a chance to run
threads->yield();
yield();
# Lists of non-detached threads
my @threads = threads->list();
my $thread_count = threads->list();
my @running = threads->list(threads::running);
my @joinable = threads->list(threads::joinable);
# Test thread objects
if ($thr1 == $thr2) {
...
}
# Manage thread stack size
$stack_size = threads->get_stack_size();
$old_size = threads->set_stack_size(32*4096);
# Create a thread with a specific context and stack size
my $thr = threads->create({ 'context' => 'list',
'stack_size' => 32*4096,
'exit' => 'thread_only' },
\&foo);
# Get thread's context
my $wantarray = $thr->wantarray();
# Check thread's state
if ($thr->is_running()) {
sleep(1);
}
if ($thr->is_joinable()) {
$thr->join();
}
# Send a signal to a thread
$thr->kill('SIGUSR1');
# Exit a thread
threads->exit();
Since Perl 5.8, thread programming has been available using a model called interpreter threads which provides a new Perl interpreter for each thread, and, by default, results in no data or state information being shared between threads.
(Prior to Perl 5.8, 5005threads was available through the Thread.pm
API. This threading model has been deprecated, and was removed as of Perl 5.10.0.)
As just mentioned, all variables are, by default, thread local. To use shared variables, you need to also load threads::shared:
use threads;
use threads::shared;
When loading threads::shared, you must use threads
before you use threads::shared
. (threads
will emit a warning if you do it the other way around.)
It is strongly recommended that you enable threads via use threads
as early as possible in your script.
If needed, scripts can be written so as to run on both threaded and non-threaded Perls:
my $can_use_threads = eval 'use threads; 1';
if ($can_use_threads) {
# Do processing using threads
...
} else {
# Do it without using threads
...
}
This will create a new thread that will begin execution with the specified entry point function, and give it the ARGS list as parameters. It will return the corresponding threads object, or undef
if thread creation failed.
FUNCTION may either be the name of a function, an anonymous subroutine, or a code ref.
my $thr = threads->create('func_name', ...);
# or
my $thr = threads->create(sub { ... }, ...);
# or
my $thr = threads->create(\&func, ...);
The ->new()
method is an alias for ->create()
.
This will wait for the corresponding thread to complete its execution. When the thread finishes, ->join()
will return the return value(s) of the entry point function.
The context (void, scalar or list) for the return value(s) for ->join()
is determined at the time of thread creation.
# Create thread in list context (implicit)
my ($thr1) = threads->create(sub {
my @results = qw(a b c);
return (@results);
});
# or (explicit)
my $thr1 = threads->create({'context' => 'list'},
sub {
my @results = qw(a b c);
return (@results);
});
# Retrieve list results from thread
my @res1 = $thr1->join();
# Create thread in scalar context (implicit)
my $thr2 = threads->create(sub {
my $result = 42;
return ($result);
});
# Retrieve scalar result from thread
my $res2 = $thr2->join();
# Create a thread in void context (explicit)
my $thr3 = threads->create({'void' => 1},
sub { print("Hello, world\n"); });
# Join the thread in void context (i.e., no return value)
$thr3->join();
See "THREAD CONTEXT" for more details.
If the program exits without all threads having either been joined or detached, then a warning will be issued.
Calling ->join()
or ->detach()
on an already joined thread will cause an error to be thrown.
Makes the thread unjoinable, and causes any eventual return value to be discarded. When the program exits, any detached threads that are still running are silently terminated.
If the program exits without all threads having either been joined or detached, then a warning will be issued.
Calling ->join()
or ->detach()
on an already detached thread will cause an error to be thrown.
Class method that allows a thread to detach itself.