threads(3perl)

๐Ÿ’– threads(3perl) ๐Ÿ’– โ€” the Perl Programmers Reference Guide page about interpreter-based threads, but make it make sense ๐Ÿฆ‹

okay so hi bestie ๐Ÿ‘‹ this is the threads manual page from the Perl Programmers Reference Guide, and it's... a lot. It's giving "assigned reading nobody warned you about." Grab a snack. ๐Ÿ“


๐ŸŒธ NAME ๐ŸŒธ

threads โ€” Perl interpreter-based threads. that's the whole glamour, that's the whole rรฉsumรฉ. ๐Ÿ’…

โœจ VERSION โœจ

This document describes threads version 2.45. iconic, noted, moving on. ๐ŸŽ€

๐Ÿšจ WARNING ๐Ÿšจ

okay so before we do literally anything else, bestie, please read this part. I'm not being dramatic (I'm being a little dramatic), but this is the main character of the whole page and her energy is caution.

The "interpreter-based threads" that Perl gives you are not the fast, lightweight, multitasking dream machine you might expect or hope for. That's not me being shady, that's literally the doc. ๐Ÿ˜ญ

The way these threads are implemented makes them very easy to misuse. And it's not just "oops my bad" easy โ€” it's like, genuinely. Only a few people actually know how to use them correctly, or would even be able to help you out if things go sideways. ๐Ÿซถ

And the official word? Using interpreter-based threads in perl is officially discouraged. Yeah. That's the sentence. The she has spoken. ๐Ÿ’€

So like... proceed, but proceed knowing. ๐Ÿงš


๐ŸŒˆ SYNOPSIS ๐ŸŒˆ

okay here's the whole vibe in code form, every single line, no notes from me, just pure unfiltered threads:

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();

and that's just the trailer, bestie ๐ŸŽฌ โ€” there's so much more coming. don't go anywhere. ๐Ÿฆ‹โœจ

โœจ DESCRIPTION โœจ

okay so bestie, real talk: since Perl 5.8, thread programming has been available using a model called interpreter threads ๐Ÿ’… โ€” meaning every thread gets its own brand-new Perl interpreter, and by default that means no data and no state info is shared between threads. like, none. it's giving "separate little universes" ๐ŸŒŒ.

(and before Perl 5.8? there was 5005threads, available through the Thread.pm API. that threading model has been deprecated, and it got removed as of Perl 5.10.0. rip bozo, we don't talk about her ๐Ÿ’€.)

so yeah, as I just said โ€” all variables are, by default, thread local. if you want shared variables, you also need to load threads::shared:

use threads;
use threads::shared;
๐Ÿซถ very important order alert: when you load threads::shared, you must use threads before you use threads::shared. if you do it the other way around, threads will emit a warning. don't do it backwards, bestie, I'm begging ๐Ÿ™ˆ.

it is strongly recommended that you enable threads via use threads as early as possible in your script. early bird gets the threads ๐Ÿฆโœจ.

and if you need to, you can write scripts that 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
    ...
}

like, flexible queen behavior ๐Ÿ‘‘.


$thr = threads->create(FUNCTION, ARGS)

this one creates a new thread that starts executing with the entry point function you specify, and hands it the ARGS list as its parameters. it returns the matching threads object โ€” or undef if thread creation failed ๐Ÿ˜ญ.

FUNCTION can be any of these:

  • 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, ...);

also, the ->new() method is an alias for ->create(). same energy, different name ๐Ÿ’ซ.


$thr->join()

this waits for the corresponding thread to finish doing its thing. once the thread completes, ->join() returns the return value(s) of the entry point function. ate and left no crumbs ๐Ÿฝ๏ธ.

the context (void, scalar or list) used for the return value(s) of ->join() is decided at the time of thread creation. so like, decide early, babe.

# 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();

peep "THREAD CONTEXT" for the full tea ๐Ÿต.

โš ๏ธ if the program exits without all threads having either been joined or detached, a warning will be issued. the perl police will know โœจ.
๐Ÿ˜ญ calling ->join() or ->detach() on an already joined thread will cause an error to be thrown.

$thr->detach()

makes the thread unjoinable, and any eventual return value gets discarded. bye bye return value ๐Ÿ‘‹. 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, a warning will be issued.
๐Ÿ˜ญ calling ->join() or ->detach() on an already detached thread will cause an error to be thrown.

threads->detach()

class method that lets a thread detach itself. independent icon behavior ๐Ÿ’…โœจ.


threads->self()

class method that lets a thread get its own threads object. know thyself, bestie ๐Ÿชž.


$thr->tid()

returns the ID of the thread. thread IDs are unique integers, the main thread in a program is 0, and it increments by 1 for every thread created. counting starts at zero, periodt ๐Ÿ”ข.


threads->tid()

class method that lets a thread get its own ID. yass, self-knowledge ๐ŸŒธ.


"$thr"

if you add the stringify import option to your use threads declaration, then using a threads object in a string or a string context (like as a hash key) will make its ID get used as the value:

use threads qw(stringify);

my $thr = threads->create(...);
print("Thread $thr started\n");  # Prints: Thread 1 started

look at her, stringifying so prettily ๐ŸŽ€.


threads->object($tid)

this returns the threads object for the active thread associated with the thread ID you pass. if $tid is the value for the current thread, this call works exactly the same as ->self().

otherwise, it returns undef if:

  • there is no thread associated with the TID,
  • the thread is joined or detached,
  • no TID is specified,
  • or the specified TID is undef.

no thread, no object, no drama ๐Ÿ™ˆ.


threads->yield()

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. so like... it's a vibe check, not a promise, yk? ๐ŸŒˆ.

you can also do use threads qw(yield), and then just call yield() straight up in your code. convenient queen ๐Ÿ‘‘.


threads->list()

threads->list(threads::all)

threads->list(threads::running)

threads->list(threads::joinable)

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. go girlies go ๐Ÿƒโ€โ™€๏ธ.

with a false argument (using threads::joinable), returns a list of all non-joined, non-detached threads objects that have finished running โ€” i.e., the ones for which ->join() will not block. done and dusted โœจ.


$thr1->equal($thr2)

tests whether 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.) twin check ๐Ÿ‘ฏโ€โ™€๏ธ.


async BLOCK;

async creates a thread to execute the block immediately following it. this block is treated as an anonymous subroutine, so it must have a semicolon after the closing brace. like threads->create(), async returns a threads object. don't forget that semicolon or the syntax errors will humble you ๐Ÿ’€.


$thr->error()

threads are executed in an eval context. this method returns undef if the thread terminates normally. otherwise it returns the value of $@ associated with the thread's execution status in its eval context. receipts, basically ๐Ÿงพ.


$thr->_handle()

this private method returns a pointer (i.e., the memory location expressed as an unsigned integer) to 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. so like... not for casuals, this is deep lore territory ๐Ÿ”ฎ.


threads->_handle()

class method that lets a thread get its own handle. self-service, we love to see it ๐Ÿซถ.


๐Ÿšช EXITING A THREAD ๐Ÿšช

the usual method for terminating a thread is to return() from the entry point function with the appropriate return value(s). clean exit, iconic, no mess ๐Ÿ’….


threads->exit()

if you need to, 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). same thing, bestie โœจ.


threads->exit(status)

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).


die()

calling die() in a thread indicates an abnormal exit for the thread ๐Ÿ˜ญ. any $SIG{__DIE__} handler in the thread gets called first, and then the thread exits with a warning message that will contain any arguments passed in the die() call. dramatic exit, but make it informative.


exit(status)

๐Ÿ”ฅ VERY IMPORTANT, READ TWICE: 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. do not do this, I'm so serious, that's the whole app bestie ๐Ÿ’€.

if exit() really is needed, then consider using the following:

threads->exit() if threads->can('exit');   # Thread friendly
exit(status);

use threads 'exit' => 'threads_only'

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. it's giving "no collateral damage" ๐ŸŒธ.

โš ๏ธ because of its global effect, this setting should not be used inside modules or the like. global settings in modules = chaos, and not the fun kind.

the main thread is unaffected by this setting.


threads->create({'exit' => 'thread_only'}, ...)

this overrides the default behavior of exit() only inside the newly created thread. targeted, precise, main character energy ๐Ÿ‘‘.


$thr->set_thread_exit_only(boolean)

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.


threads->set_thread_exit_only(boolean)

class method for use inside a thread, to change its own behavior for exit().

the main thread is unaffected by this call. she stays unbothered, as always ๐Ÿ’œ.

๐ŸŒธ THREAD STATE ๐ŸŒธ

okay bestie, these four are the little vibe-check booleans that tell you what's going on with a thread. obsessed with them honestly. ๐Ÿซถ

  • $thr->is_running() โ€” returns true if the thread is still running, aka its entry point function hasn't finished or exited yet.
  • $thr->is_joinable() โ€” returns true if the thread has finished running, is not detached, and hasn't been joined yet. translation: it's ready to be joined, and calling $thr->join() won't block. ๐Ÿ’…
  • $thr->is_detached() โ€” returns true if the thread has been detached.
  • threads->is_detached() โ€” class method moment โœจ lets a thread figure out whether it itself is detached or not.

๐Ÿฆ‹ THREAD CONTEXT ๐Ÿฆ‹

so, same energy as subroutines: the type of value your thread's entry point function gives back can depend on the thread's context โ€” list, scalar, or void. the thread's context gets determined at thread creation. and it has to work that way, because the entry point function needs that context available to it via wantarray(). then the thread can hand back a value of the right type from ->join(). no cap. ๐Ÿซก

๐Ÿ’… Explicit context

since creating a thread and joining a thread can totally happen in different contexts, you might wanna state the context explicitly to the entry point function. you do that by calling ->create() with a hash reference as the first argument:

my $thr = threads->create({'context' => 'list'}, \&foo);
...
my @results = $thr->join();

in that example, the threads object comes back to the parent thread in scalar context, and the entry point function foo gets called in list (array) context so the parent thread can receive a list (array) from the ->join() call. and yes โ€” 'array' is synonymous with 'list'. โœจ

similarly, if you need the threads object but your thread isn't returning a value at all (that's void context, bb), you'd do this:

my $thr = threads->create({'context' => 'void'}, \&foo);
...
$thr->join();

you can also use the context type itself as the key in the hash reference, followed by a true value:

threads->create({'scalar' => 1}, \&foo);
...
my ($thr) = threads->list();
my $result = $thr->join();

๐ŸŒˆ Implicit context

if you don't state it explicitly, the thread's context is implied from the context of the ->create() call. sneaky but iconic:

# Create thread in list context
my ($thr) = threads->create(...);

# Create thread in scalar context
my $thr = threads->create(...);

# Create thread in void context
threads->create(...);

โญ $thr->wantarray() โญ

returns the thread's context, same manner as wantarray(). simple as that.

๐ŸŽ€ threads->wantarray() ๐ŸŽ€

class method that returns the current thread's context. it gives you the same value as running wantarray() inside the current thread's entry point function. iykyk.


๐Ÿงš THREAD STACK SIZE ๐Ÿงš

okay so here's the tea โ˜• โ€” the default per-thread stack size is wildly different across platforms, and it's almost always way, way more than most applications actually need. on Win32, Perl's makefile explicitly sets the default stack to 16 MB; on most other platforms the system default gets used, which again may be so much larger than needed.

but if you tune the stack size so it actually reflects what your app needs? you can seriously cut down memory usage and run more threads at the same time. that's the dream, bestie. ๐Ÿ’–

heads up: on Windows, address space allocation granularity is 64 KB, so setting the stack smaller than that on Win32 Perl won't save you any more memory. periodt.
  • threads->get_stack_size(); โ€” returns the current default per-thread stack size. the default is zero, which means the system default stack size is currently in use.
  • $size = $thr->get_stack_size(); โ€” returns the stack size for a particular thread. a return value of zero means the system default stack size was used for that thread.
  • $old_size = threads->set_stack_size($new_size); โ€” sets a new default per-thread stack size, and returns the previous setting. some more deets:
    • some platforms have a minimum thread stack size. trying to set the stack size below that value will result in a warning, and the minimum stack size will be used.
    • some Linux platforms have a maximum stack size. setting a stack size that's too large will cause thread creation to fail. ๐Ÿ’€
    • if needed, $new_size will be rounded up to the next multiple of the memory page size (usually 4096 or 8192).
    • threads created after the stack size is set will then either call pthread_attr_setstacksize() (for pthreads platforms), or supply the stack size to CreateThread() (for Win32 Perl).
    • (obviously, this call does not affect any currently extant threads. they're already out here living their lives.)
  • use threads ('stack_size' => VALUE); โ€” sets the default per-thread stack size at the start of the application.
  • $ENV{'PERL5_ITHREADS_STACK_SIZE'} โ€” the default per-thread stack size may also be set at the start of the application through this environment variable:
PERL5_ITHREADS_STACK_SIZE=1048576
export PERL5_ITHREADS_STACK_SIZE
perl -e'use threads; print(threads->get_stack_size(), "\n")'

this value overrides any "stack_size" parameter given to use threads. its primary purpose is to permit setting the per-thread stack size for legacy threaded applications.

  • threads->create({'stack_size' => VALUE}, FUNCTION, ARGS) โ€” to specify a particular stack size for any individual thread, call ->create() with a hash reference as the first argument:
my $thr = threads->create({'stack_size' => 32*4096},
                          \&foo, @args);
  • $thr2 = $thr1->create(FUNCTION, ARGS) โ€” this creates a new thread ($thr2) that inherits the stack size from an existing thread ($thr1). it's shorthand for the following:
my $stack_size = $thr1->get_stack_size();
my $thr2 = threads->create({'stack_size' => $stack_size},
                           FUNCTION, ARGS);

๐Ÿ”ฅ THREAD SIGNALLING ๐Ÿ”ฅ

when safe signals is in effect (that's the default behavior โ€” see the "Unsafe signals" section for more details), signals may be sent to and acted upon by individual threads. main character energy for real.

  • $thr->kill('SIG...'); โ€” sends the specified signal to the thread. signal names and (positive) signal numbers are the same as those supported by kill(). for example, 'SIGTERM', 'TERM' and (depending on the OS) 15 are all valid arguments to ->kill().

it returns the thread object to allow for method chaining:

$thr->kill('SIG...')->join();

signal handlers need to be set up in the threads for the signals they're expected to act upon. here's an example for cancelling a thread:

use threads;

sub thr_func
{
    # Thread 'cancellation' signal handler
    $SIG{'KILL'} = sub { threads->exit(); };

    ...
}

# Create a thread
my $thr = threads->create('thr_func');

...

# Signal the thread to terminate, and then detach
# it so that it will get cleaned up automatically
$thr->kill('KILL')->detach();

and here's another simplistic example that illustrates the use of thread signalling together with a semaphore, giving you rudimentary suspend and resume capabilities:

use threads;
use Thread::Semaphore;

sub thr_func
{
    my $sema = shift;

    # Thread 'suspend/resume' signal handler
    $SIG{'STOP'} = sub {
        $sema->down();      # Thread suspended
        $sema->up();        # Thread resumes
    };

    ...
}

# Create a semaphore and pass it to a thread
my $sema = Thread::Semaphore->new();
my $thr = threads->create('thr_func', $sema);

# Suspend the thread
$sema->down();
$thr->kill('STOP');

...

# Allow the thread to continue
$sema->up();
CAVEAT: the thread signalling capability provided by this module does not actually send signals via the OS. it emulates signals at the Perl level, so that signal handlers are called in the appropriate thread. for example, sending $thr->kill('STOP') does not actually suspend a thread (or the whole process! ๐Ÿ˜ญ) โ€” but it does cause a $SIG{'STOP'} handler to be called in that thread (as illustrated above).

as such, signals that would normally not be appropriate to use in the kill() command (e.g., kill('KILL', $$)) are okay to use with the ->kill() method (again, as illustrated above).

correspondingly, sending a signal to a thread does not disrupt the operation the thread is currently working on: the signal will be acted upon after the current operation has completed. for instance, if the thread is stuck on an I/O call, sending it a signal will not cause the I/O call to be interrupted so that the signal is acted upon immediately.

sending a signal to a terminated/finished thread is ignored.


๐ŸŒŸ WARNINGS ๐ŸŒŸ

  • Perl exited with active threads: โ€” if the program exits without all threads having either been joined or detached, then this warning gets issued.

NOTE: if the main thread exits, then this warning cannot be suppressed using no warnings 'threads'; as suggested below.

  • Thread creation failed: pthread_create returned # โ€” see the appropriate man page for pthread_create to determine the actual cause for the failure.
  • Thread # terminated abnormally: ... โ€” a thread terminated in some manner other than just returning from its entry point function, or by using threads->exit(). for example, the thread may have terminated because of an error, or by using die.
  • Using minimum thread stack size of # โ€” some platforms have a minimum thread stack size. trying to set the stack size below that value will result in the above warning, and the stack size will be set to the minimum.
  • Thread creation failed: pthread_attr_setstacksize(SIZE) returned 22 โ€” the specified SIZE exceeds the system's maximum stack size. use a smaller value for the stack size.

if needed, thread warnings can be suppressed by using:

no warnings 'threads';

in the appropriate scope. ๐Ÿซถ

๐Ÿ’€ ERRORS ๐Ÿ’€

okay bestie, here's the emotional damage section โ€” the error messages that can pop out and ruin your whole afternoon. let's vibe check each one so you're never caught off guard ๐Ÿซถ


๐Ÿ™ˆ This Perl not built to support threads

so the specific copy of Perl you're trying to use? yeah, it was not built using the useithreads configuration option. that's it, that's the whole crime. ๐Ÿ˜ญ

and here's the part that lowkey hurts: having threads support requires all of Perl and all of the XS modules in the Perl installation to be rebuilt. it is not just a question of adding the threads module, bestie. it's giving full renovation, not a fresh coat of paint. ๐Ÿ’…

i.e., threaded and non-threaded Perls are binary incompatible โ€” they simply do not speak the same language, no cap. ๐Ÿฆ‹


๐Ÿ”’ Cannot change stack size of an existing thread

the stack size of currently extant threads cannot be changed. periodt. once a thread exists, that number is locked in like a screenshot. ๐Ÿ“ธ

therefore, this following call? it results in the above error:

$thr->set_stack_size($size);

so don't do that to a thread that's already living its life. โœจ


๐Ÿšจ Cannot signal threads without safe signals

safe signals must be in effect to use the ->kill() signalling method. that's the rule, no exceptions, the door is bolted. ๐Ÿ”

see "Unsafe signals" for more details โ€” go read that bit if you're curious, it's important iykyk. ๐Ÿ‘‘


โ“ Unrecognized signal name: ...

the particular copy of Perl that you're trying to use does not support the specified signal being used in a ->kill() call. so if you're throwing a signal name at it that it doesn't recognise, it will simply โœจ not โœจ. ๐ŸŒˆ

double-check your signal name before you send it, bestie. ๐Ÿ™ˆ


๐Ÿ’€ BUGS AND LIMITATIONS ๐Ÿ’€

okay bestie, before you go off and post a bug report, pls pls pls consult the docs, and maybe drop a message in the discussion forum first to see if what you've run into is already a known problem. saves everybody time, fr fr ๐Ÿซถ

๐Ÿงต Thread-safe modules

If you're out here writing modules that might get used in threaded apps, go read "Making your module threadsafe" in perlmod โ€” especially if your module touches non-Perl data or XS code. that's the vibe check you need before shipping ๐Ÿ’…

๐Ÿ˜ญ Using non-thread-safe modules

ngl, you will run into Perl modules that are not thread-safe. like, they might crash the Perl interpreter mid-execution, or just dump core on termination. it's giving chaos. depending on the module and what your app actually needs, you might be able to work around it though.

If the module only ever gets used inside a thread, try loading it from inside the thread entry point function using require (and import if you need it):

sub thr_func
{
    require Unsafe::Module
    # Unsafe::Module->import(...);

    ....
}

If the module is needed inside the main thread, try reworking your app so the module gets loaded (again, using require and ->import()) after any threads are started, and in such a way that no other threads get started afterwards. timing is everything ๐Ÿ’ซ

If none of that works, or it's just not good enough for your app, then file a bug report on <https://rt.cpan.org/Public/> against the problematic module. make it their problem bestie โœจ

๐Ÿง  Memory consumption

On most systems, creating and destroying threads frequently and continually can make the memory footprint of the Perl interpreter just keep growing and growing. no thank you. like yeah it's simple to just launch threads and then ->join() or ->detach() them, but for long-lived applications it's way better to maintain a pool of threads and reuse them for the work you need โ€” using queues to notify threads of pending work.

The CPAN distribution of this module contains a simple example (examples/pool_reuse.pl) illustrating the creation, use and monitoring of a pool of reusable threads. go look, it's iconic ๐Ÿ‘‘

๐Ÿ“‚ Current working directory

On all platforms except MSWin32, the setting for the current working directory is shared among all threads. so changing it in one thread (e.g., using chdir()) will affect all the threads in the application. one thread changes the vibe, everybody moves ๐Ÿ˜ญ

On MSWin32, each thread maintains its own the current working directory setting.

๐ŸŒ Locales

Prior to Perl 5.28, locales could not be used with threads, due to various race conditions. Starting in that release, on systems that implement thread-safe locale functions, threads can be used, with some caveats. This includes Windows starting with Visual Studio 2005, and systems compatible with POSIX 2008. See "Multi-threaded operation" in perllocale.

Each thread (except the main thread) is started using the C locale. The main thread is started like all other Perl programs; see "ENVIRONMENT" in perllocale. You can switch locales in any thread as often as you like. go off ๐Ÿฆ‹

If you want to inherit the parent thread's locale, you can, in the parent, set a variable like so:

$foo = POSIX::setlocale(LC_ALL, NULL);

and then pass to threads->create() a sub that closes over $foo. Then, in the child, you say

POSIX::setlocale(LC_ALL, $foo);

Or you can use the facilities in threads::shared to pass $foo; or if the environment hasn't changed, in the child, do

POSIX::setlocale(LC_ALL, "");

๐ŸŒฑ Environment variables

Currently, on all platforms except MSWin32, all system calls (e.g., using system() or back-ticks) made from threads use the environment variable settings from the main thread. In other words, changes made to %ENV in a thread will not be visible in system calls made by that thread. the audacity tbh ๐Ÿ™ˆ

To work around this, set environment variables as part of the system call. For example:

my $msg = 'hello';
system("FOO=$msg; echo \$FOO");   # Outputs 'hello' to STDOUT

On MSWin32, each thread maintains its own set of environment variables.

๐Ÿšจ Catching signals

Signals are caught by the main thread (thread ID = 0) of a script. So setting up signal handlers in threads for purposes other than "THREAD SIGNALLING" as documented above will not accomplish what is intended. sorry bestie ๐Ÿ’€

This is especially true if you're trying to catch SIGALRM in a thread. To handle alarms in threads, set up a signal handler in the main thread, and then use "THREAD SIGNALLING" to relay the signal to the thread:

# Create thread with a task that may time out
my $thr = threads->create(sub {
    threads->yield();
    eval {
        $SIG{ALRM} = sub { die("Timeout\n"); };
        alarm(10);
        ...  # Do work here
        alarm(0);
    };
    if ($@ =~ /Timeout/) {
        warn("Task in thread timed out\n");
    }
};

# Set signal handler to relay SIGALRM to thread
$SIG{ALRM} = sub { $thr->kill('ALRM') };

... # Main thread continues working

๐Ÿ‘ฉโ€๐Ÿ‘ง Parent-child threads

On some platforms, it might not be possible to destroy parent threads while there are still existing child threads. family drama, can't escape it ๐Ÿซ 

โš ๏ธ Unsafe signals

Since Perl 5.8.0, signals have been made safer in Perl by postponing their handling until the interpreter is in a safe state. See "Safe Signals" in perl58delta and "Deferred Signals (Safe Signals)" in perlipc for more details.

Safe signals is the default behavior, and the old, immediate, unsafe signalling behavior is only in effect in the following situations:

  • Perl has been built with PERL_OLD_SIGNALS (see perl -V).
  • The environment variable PERL_SIGNALS is set to unsafe (see "PERL_SIGNALS" in perlrun).
  • The module Perl::Unsafe::Signals is used.

If unsafe signals is in effect, then signal handling is not thread-safe, and the ->kill() signalling method cannot be used. big yikes, do not recommend ๐Ÿ”ฅ

๐Ÿชž Identity of objects returned from threads

When a value is returned from a thread through a join operation, the value and everything that it references is copied across to the joining thread, in much the same way that values are copied upon thread creation. This works fine for most kinds of value, including arrays, hashes, and subroutines. The copying recurses through array elements, reference scalars, variables closed over by subroutines, and other kinds of reference.

However, everything referenced by the returned value is a fresh copy in the joining thread, even if a returned object had in the child thread been a copy of something that previously existed in the parent thread. After joining, the parent will therefore have a duplicate of each such object. This sometimes matters, especially if the object gets mutated; this can especially matter for private data to which a returned subroutine provides access. two of the same thing, but not the same thing. it's giving clone arc ๐Ÿ’…

๐ŸŽ Returning blessed objects from threads

Returning blessed objects from threads does not work. Depending on the classes involved, you may be able to work around this by returning a serialized version of the object (e.g., using Data::Dumper or Storable), and then reconstituting it in the joining thread. If you're using Perl 5.10.0 or later, and if the class supports shared objects, you can pass them via shared queues.

๐Ÿ END blocks in threads

It is possible to add END blocks to threads by using require or eval with the appropriate code. These END blocks will then be executed when the thread's interpreter is destroyed (i.e., either during a ->join() call, or at program termination).

However, calling any threads methods in such an END block will most likely fail (e.g., the application may hang, or generate an error) due to mutexes that are needed to control functionality within the threads module. ๐Ÿ’€

For this reason, the use of END blocks in threads is strongly discouraged. just don't, bestie.

๐Ÿ“ Open directory handles

In perl 5.14 and higher, on systems other than Windows that do not support the fchdir C function, directory handles (see opendir) will not be copied to new threads. You can use the d_fchdir variable in Config.pm to determine whether your system supports it.

In prior perl versions, spawning threads with open directory handles would crash the interpreter. [perl #75154] <https://rt.perl.org/rt3/Public/Bug/Display.html?id=75154>

๐Ÿซฅ Detached threads and global destruction

If the main thread exits while there are detached threads which are still running, then Perl's global destruction phase is not executed โ€” because otherwise certain global structures that control the operation of threads and that are allocated in the main thread's memory may get destroyed before the detached thread is destroyed. chaos avoidance, honestly valid ๐Ÿ˜Œ

If you are using any code that requires the execution of the global destruction phase for clean up (e.g., removing temp files), then do not use detached threads โ€” instead, join all threads before exiting the program. periodt.

๐Ÿ› Perl Bugs and the CPAN Version of threads

Support for threads extends beyond the code in this module (i.e., threads.pm and threads.xs), and into the Perl interpreter itself. Older versions of Perl contain bugs that may manifest themselves despite using the latest version of threads from CPAN. There is no workaround for this other than upgrading to the latest version of Perl. upgrade or suffer, iykyk ๐ŸŒˆ

Even with the latest version of Perl, it is known that certain constructs with threads may result in warning messages concerning leaked scalars or unreferenced scalars. However, such warnings are harmless, and may safely be ignored. no cap.

You can search for threads related bug reports at <https://rt.cpan.org/Public/>. If needed submit any new bugs, problems, patches, etc. to: <https://rt.cpan.org/Public/Dist/Display.html?Name=threads>


โœจ REQUIREMENTS โœจ

Perl 5.8.0 or later. that's it, that's the bar ๐ŸŽ€

๐Ÿ‘€ SEE ALSO (the ~girlies~ and resources that go with this) ๐Ÿ‘€


๐ŸŽ€ AUTHOR (the masterminds) ๐ŸŽ€

  • Artur Bergman <sky AT crucially DOT net> โ€” the OG ๐Ÿ‘‘
  • CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org> โ€” took it to CPAN, slay ๐Ÿ’–

๐Ÿ“œ LICENSE ๐Ÿ“œ

threads is released under the same license as Perl. That's it, that's the vibe. ๐Ÿ’œ


๐Ÿ’ ACKNOWLEDGEMENTS (the group chat that made it happen) ๐Ÿ’

  • Richard Soderberg <perl AT crystalflame DOT net> โ€” helped out tons, trying to find reasons for races and other weird bugs! ๐Ÿ›๐Ÿ˜ญ
  • Simon Cozens <simon AT brecon DOT co DOT uk> โ€” being there to answer zillions of annoying questions ๐Ÿซถ
  • Rocco Caputo <troc AT netrus DOT net> ๐ŸŒˆ
  • Vipul Ved Prakash <mail AT vipul DOT net> โ€” helping with debugging ๐Ÿ”
  • Dean Arnold <darnold AT presicient DOT com> โ€” stack size API ๐Ÿงฑโœจ

okay that's the whole page bestie, we did it ๐Ÿ’…โœจ This was threads(3perl) for perl v5.44.0, dated 2026-10-17 โ€” go forth and thread safely, mwah ๐Ÿ’–๐Ÿฆ‹๐ŸŒธ

๐Ÿ“ฆ where this page comes from
  • arch rolling: perl 5.44.0-1 ยท Artistic-1.0-Perl AND GPL-1.0-or-later
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms