threads - Perl interpreter-based threads
This document describes threads version 1.86
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.
Class method that allows a thread to obtain its own threads object.
Returns the ID of the thread. Thread IDs are unique integers with the main thread in a program being 0, and incrementing by 1 for every thread created.
Class method that allows a thread to obtain its own ID.
If you add the stringify
import option to your use threads
declaration, then using a threads object in a string or a string context (e.g., as a hash key) will cause its ID to be used as the value:
use threads qw(stringify);
my $thr = threads->create(...);
print("Thread $thr started...\n"); # Prints out: Thread 1 started...
This will return the threads object for the active thread associated with the specified thread ID. If $tid
is the value for the current thread, then this call works the same as ->self()
. Otherwise, returns undef
if there is no thread associated with the TID, if the thread is joined or detached, if no TID is specified or if the specified TID is undef.
This is a suggestion to the OS to let this thread yield CPU time to other threads. What actually happens is highly dependent upon the underlying thread implementation.
You may do use threads qw(yield)
, and then just use yield()
in your code.
With no arguments (or using threads::all
) and in a list context, returns a list of all non-joined, non-detached threads objects. In a scalar context, returns a count of the same.
With a true argument (using threads::running
), returns a list of all non-joined, non-detached threads objects that are still running.
With a false argument (using threads::joinable
), returns a list of all non-joined, non-detached threads objects that have finished running (i.e., for which ->join()
will not block).
Tests if two threads objects are the same thread or not. This is overloaded to the more natural forms:
if ($thr1 == $thr2) {
print("Threads are the same\n");
}
# or
if ($thr1 != $thr2) {
print("Threads differ\n");
}
(Thread comparison is based on thread IDs.)
async
creates a thread to execute the block immediately following it. This block is treated as an anonymous subroutine, and so must have a semicolon after the closing brace. Like threads->create()
, async
returns a threads object.
Threads are executed in an eval
context. This method will return undef
if the thread terminates normally. Otherwise, it returns the value of $@
associated with the thread's execution status in its eval
context.
This private method returns the memory location of the internal thread structure associated with a threads object. For Win32, this is a pointer to the HANDLE
value returned by CreateThread
(i.e., HANDLE *
); for other platforms, it is a pointer to the pthread_t
structure used in the pthread_create
call (i.e., pthread_t *
).
This method is of no use for general Perl threads programming. Its intent is to provide other (XS-based) thread modules with the capability to access, and possibly manipulate, the underlying thread structure associated with a Perl thread.
Class method that allows a thread to obtain its own handle.
The usual method for terminating a thread is to return() from the entry point function with the appropriate return value(s).
If needed, a thread can be exited at any time by calling threads->exit()
. This will cause the thread to return undef
in a scalar context, or the empty list in a list context.
When called from the main thread, this behaves the same as exit(0)
.
When called from a thread, this behaves like threads->exit()
(i.e., the exit status code is ignored).
When called from the main thread, this behaves the same as exit(status)
.
Calling die()
in a thread indicates an abnormal exit for the thread. Any $SIG{__DIE__}
handler in the thread will be called first, and then the thread will exit with a warning message that will contain any arguments passed in the die()
call.
Calling exit() inside a thread causes the whole application to terminate. Because of this, the use of exit()
inside threaded code, or in modules that might be used in threaded applications, is strongly discouraged.
If exit()
really is needed, then consider using the following:
threads->exit() if threads->can('exit'); # Thread friendly
exit(status);
This globally overrides the default behavior of calling exit()
inside a thread, and effectively causes such calls to behave the same as threads->exit()
. In other words, with this setting, calling exit()
causes only the thread to terminate.
Because of its global effect, this setting should not be used inside modules or the like.
The main thread is unaffected by this setting.
This overrides the default behavior of exit()
inside the newly created thread only.
This can be used to change the exit thread only behavior for a thread after it has been created. With a true argument, exit()
will cause only the thread to exit. With a false argument, exit()
will terminate the application.
The main thread is unaffected by this call.
Class method for use inside a thread to change its own behavior for exit()
.
The main thread is unaffected by this call.