threads(3pm)

okay bestie, buckle up: this is threads(3pm) from the Perl Programmers Reference Guide πŸ¦‹ β€” part 1 of 6, and yes, there’s more coming πŸ’…

πŸ’– NAME πŸ’–

threads β€” Perl interpreter-based threads ✨

🌈 VERSION 🌈

This document describes threads version 2.43 πŸŽ€

🚨 WARNING 🚨

okay so the β€œinterpreter-based threads” provided by Perl are not the fast, lightweight multitasking system you might expect or hope for 😭. No cap. 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.

✨ SYNOPSIS ✨

here’s the group-chat demo reel, bestie β€” every line is exactly the code you’d type πŸ‘‘:

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

πŸ’– DESCRIPTION πŸ’–

Okay so bestie, story time: ever since Perl 5.8, we've had thread programming via this model called interpreter threads β€” which literally gives every single thread its own brand-new Perl interpreter, and by default means no data or state info gets shared between threads. Zero. Nada. Each thread is in its own little world, main character energy, no crossover episodes. ✨

(And before Perl 5.8? There was 5005threads, available through the "Thread.pm" API. That model is deprecated, bestie β€” it got removed as of Perl 5.10.0. Gone gone. πŸ’€)

So like I just said β€” all variables are thread local by default. If you want shared variables you gotta also load threads::shared:

use threads;
use threads::shared;
⚠️ Order matters, queen! When you load threads::shared, you must "use threads" before you "use threads::shared". Do it the other way around and "threads" will emit a warning at you. πŸ™ˆ

It is strongly recommended that you enable threads via "use threads" as early as possible in your script. Like, first thing. Before the drama starts. 🫢

And if you need your script to run on both threaded and non-threaded Perls (iconic, flexible, we love), you can write it like this:

my $can_use_threads = eval 'use threads; 1';
if ($can_use_threads) {
    # Do processing using threads
    ...
} else {
    # Do it without using threads
    ...
}

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

This spawns a brand-new thread that starts executing with the entry point function you specify, and hands it the ARGS list as its parameters. It gives you back the corresponding threads object β€” or "undef" if the whole thread creation thing flopped. 😭

FUNCTION can be any of these three flavours:

  • the name of a function
  • an anonymous subroutine
  • a code ref

Like so:

my $thr = threads->create('func_name', ...);
    # or
my $thr = threads->create(sub { ... }, ...);
    # or
my $thr = threads->create(\&func, ...);

And heads up: the "->new()" method is literally just an alias for "->create()". Same vibes, different name. πŸ’…

πŸ¦‹ $thr->join() πŸ¦‹

This is you saying "okay bestie, I'll wait". It waits for the corresponding thread to finish doing its thing. And when the thread is done, "->join()" returns the return value(s) of the entry point function. πŸŽ€

Now, the context (void, scalar or list) for those return value(s) gets determined at the time of thread creation. Not at join time. Remember that, it's important.

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

Pop over to "THREAD CONTEXT" for the full tea on that. β˜•

⚠️ If the program exits without all threads having either been joined or detached, then a warning will be issued. Don't leave your threads hanging, it's rude. 😀
⚠️ And calling "->join()" or "->detach()" on a thread that's already joined will cause an error to be thrown. No double dipping.

πŸ’… $thr->detach() πŸ’…

This makes the thread unjoinable and causes any eventual return value to just be... discarded. Poof. 🫧 And when the program exits, any detached threads that are still running get silently terminated. No goodbye, no nothing.

⚠️ Same warning as before, bestie: if the program exits without all threads having either been joined or detached, then a warning will be issued.
⚠️ And calling "->join()" or "->detach()" on an already detached thread will cause an error to be thrown.

✨ threads->detach() ✨

A class method that lets a thread detach itself. Self-care, but make it concurrency. πŸ§–

🌈 threads->self() 🌈

Class method that lets a thread obtain its very own threads object. Know thyself, etc. πŸ’–

⭐ $thr->tid() ⭐

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. So 0, 1, 2, 3... you get it. πŸ”’

πŸ“ threads->tid() πŸ“

Class method that lets a thread obtain its own ID. Same energy, but from the inside.

πŸŽ€ "$thr" πŸŽ€

Here's a cute one: if you add the "stringify" import option to your "use threads" declaration, then using a threads object in a string or 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: Thread 1 started

Slay. Look at that output. πŸ‘‘

πŸ”₯ threads->object($tid) πŸ”₯

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

Otherwise? It returns "undef" if:

  • there's no thread associated with the TID
  • the thread is joined or detached
  • no TID is specified
  • the specified TID is undef

Sorry babe, that's the whole list. πŸ’€

🧚 threads->yield() 🧚

This is basically a suggestion to the OS like "hey, maybe let this thread yield CPU time to other threads? please? πŸ₯Ί" What actually happens is highly dependent upon the underlying thread implementation. So it's a vibe, not a guarantee.

Oh and you can do use threads qw(yield), and then just use yield() in your code. Convenient!

🌸 threads->list() 🌸

🌸 threads->list(threads::all) 🌸

🌸 threads->list(threads::running) 🌸

🌸 threads->list(threads::joinable) 🌸

The full breakdown, because there are options:

  • With no arguments (or using "threads::all") and in a list context, returns a list of all non-joined, non-detached thread objects. In a scalar context, returns a count of the same. Handy!
  • With a true argument (using "threads::running"), returns a list of all non-joined, non-detached thread objects that are still running.
  • With a false argument (using "threads::joinable"), returns a list of all non-joined, non-detached thread objects that have finished running β€” i.e., the ones for which "->join()" will not block. πŸ‘€

πŸ’œ $thr1->equal($thr2) πŸ’œ

Tests whether two threads objects are the same thread or not. And it's overloaded into the way more natural forms, because who has time for method calls:

if ($thr1 == $thr2) {
    print("Threads are the same\n");
}
# or
if ($thr1 != $thr2) {
    print("Threads differ\n");
}

(Thread comparison is based on thread IDs, btw. Not vibes.) πŸ’…

🫢 async BLOCK; 🫢

"async" creates a thread to execute the block that immediately follows it. That block gets treated as an anonymous subroutine β€” which means it must have a semicolon after the closing brace. Do not forget the semicolon. I'm serious. 😀

Like "threads->create()", "async" returns a threads object. Iconic and consistent.

πŸ¦‹ $thr->error() πŸ¦‹

Threads are executed in an "eval" context. So this method returns "undef" if the thread terminates normally β€” all good, no notes. Otherwise, it returns the value of $@ associated with the thread's execution status in its "eval" context. That's how you find out what went wrong. 😭

πŸŽ€ $thr->_handle() πŸŽ€

Okay, this is a private method, so don't come for it. It returns a pointer (i.e., the memory location expressed as an unsigned integer) to the internal thread structure associated with a threads object.

Platform tea:

  • For Win32, this is a pointer to the "HANDLE" value returned by "CreateThread" (i.e., "HANDLE *").
  • For other platforms, it's 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 β€” genuinely, ignore it. Its whole 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. Big brain low-level stuff. 🧠

⭐ threads->_handle() ⭐

Class method that lets a thread obtain its own handle. The inside-job version of the one above.


πŸŽ€ EXITING A THREAD πŸŽ€

The usual, normal, no-drama method for terminating a thread is to return() from the entry point function with the appropriate return value(s). That's it. That's the move. ✨

πŸ’– threads->exit() πŸ’–

If you really need to, a thread can be exited at any time by calling "threads->exit()". This causes the thread to return "undef" in a scalar context, or the empty list in a list context.

And when it's called from the main thread? This behaves the same as exit(0).

πŸ’– threads->exit(status) πŸ’–

  • When called from a thread, this behaves like "threads->exit()" β€” meaning the exit status code is ignored. Yeah. Ignored. Don't fight it.
  • When called from the main thread, this behaves the same as exit(status).

πŸ’€ die() πŸ’€

Calling die() in a thread indicates an abnormal exit for that 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 you passed in the die() call. So at least you get receipts. 😭

🚨 exit(status) 🚨

Okay this is the big scary one, listen up. Calling exit() inside a thread causes the whole application to terminate. Not just the thread. Everything. Because of this, the use of exit() inside threaded code β€” or in modules that might be used in threaded applications β€” is strongly discouraged. Please. I'm begging. πŸ™

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

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

That way you check first. Look before you leap. πŸ’…

🌈 use threads 'exit' => 'threads_only' 🌈

This globally overrides the default behaviour 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. No collateral damage. πŸŽ€

⚠️ Because of its global effect, this setting should not be used inside modules or the like. Don't be that person.

And the main thread is unaffected by this setting. It stays unbothered, living its life. 😌

πŸ¦‹ threads->create({'exit' => 'thread_only'}, ...) πŸ¦‹

This overrides the default behaviour of exit() inside the newly created thread only. Just that one. Scoped, tasteful, considerate. πŸ’…

(Yes, the value is spelled 'thread_only' here. Copy it exactly, bestie β€” don't get cute with it.)

⭐ $thr->set_thread_exit_only(boolean) ⭐

This is how you change the exit-thread-only behaviour for a thread after it's already been created. Late to the party but still welcome.

  • 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. Always the main thread. Unbothered. πŸ‘‘

🌸 threads->set_thread_exit_only(boolean) 🌸

Class method for use inside a thread to change its own behaviour for exit(). Self-determination! 🫢

And yeah β€” the main thread is unaffected by this call too. It simply does not care.

πŸ’… THREAD STATE πŸ’…

okay so these next few boolean methods are your little vibe-checkers for a thread β€” they tell you what's going on with it. use them, love them. 🫢

  • $thr->is_running() β€” returns true if the thread is still running, like, if its entry point function hasn't finished or exited yet. it's still out there living its life ✨
  • $thr->is_joinable() β€” returns true if the thread has finished running, is not detached, and hasn't been joined yet. basically: it's ready to be joined, and calling $thr->join() won't block. it's standing there with its bags packed like "bestie i'm ready, come get me" πŸŽ€
  • $thr->is_detached() β€” returns true if the thread has been detached. that's it, that's the whole method πŸ’…
  • threads->is_detached() β€” class method, so a thread can check for itself whether or not it's detached. main character energy, honestly πŸ‘‘

🌸 THREAD CONTEXT 🌸

so, just like with regular subroutines, the type of value that comes back from a thread's entry point function depends on that thread's context β€” list, scalar, or void. and here's the cute part: the thread's context gets decided at thread creation. why? because the context has to be available to the entry point function through wantarray(). then the thread can return a value of the right type from ->join(). slay 🌈

✨ Explicit context ✨

okay so because creating a thread and joining a thread can happen in totally different contexts, sometimes you wanna be explicit about which context the thread's entry point function gets. 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 the code above: the threads object comes back to the parent thread in scalar context, and the thread's 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', iykyk πŸ’–

same energy if you need the threads object but your thread isn't returning anything (i.e. void context), you'd do:

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

oh and the context type can also be used 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 just implied from the context of the ->create() call. no cap:

# 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 way wantarray() does. iconic behavior only πŸ’…
  • threads->wantarray() β€” class method that returns the current thread's context. and it returns the same value you'd get running wantarray() inside the current thread's entry point function. literally the same thing 🌟

πŸŽ€ THREAD STACK SIZE πŸŽ€

okay so the default per-thread stack size is wildly different across platforms, and it's almost always way more than most apps actually need. on Win32, Perl's makefile explicitly sets the default stack to 16 MB; on most other platforms the system default is used β€” which, again, may be so much bigger than what you need. it's giving overpacked suitcase 🧳

but here's the thing: if you tune the stack size to more accurately reflect what your app actually needs, you can significantly reduce your app's memory usage AND increase the number of simultaneously running threads. glow-up for your whole process ✨

heads up bestie: 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. don't waste your time πŸ’€
  • 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 one 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. very "here's what you were, here's what you are now" of it πŸ¦‹
    • 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 too large of a stack size 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 grandfathered in, periodt.)
  • use threads ('stack_size' => VALUE); β€” sets the default per-thread stack size at the start of the application. super convenient ⭐
  • $ENV{'PERL5_ITHREADS_STACK_SIZE'} β€” the default per-thread stack size may be set at the start of the application through the environment variable PERL5_ITHREADS_STACK_SIZE:
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. doing it for the elders 🫢

  • 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 "Unsafe signals" for the deets), signals may be sent and acted upon by individual threads. so like, per-thread signals. obsessed πŸ’–

  • $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(). and it returns the thread object so you can method chain like the icon you are:
$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 using thread signalling with a semaphore to provide 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 this module provides does not actually send signals via the OS. it emulates signals at the Perl level so that signal handlers get 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). so like, it's giving signal, not being signal πŸ’…

and because of that: 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 such that the signal is acted upon immediately. it'll wait its turn, respectfully ⭐

sending a signal to a terminated/finished thread is ignored. it's over, it's not listening, leave it alone πŸ™ˆ


πŸ”₯ 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. yeah. not even that works 😭
  • Thread creation failed: pthread_create returned # β€” see the appropriate man page for pthread_create to figure out the actual cause of the failure. detective work time πŸ”
  • 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. gone too soon πŸ’€
  • Using minimum thread stack size of # β€” some platforms have a minimum thread stack size. trying to set the stack size below this value results in the above warning, and the stack size gets set to the minimum. it's doing its best 🫢
  • 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. bestie, read the room (and the size limit) ✨

and if needed, thread warnings can be suppressed by using:

no warnings 'threads';

in the appropriate scope. manifesting a quiet, warning-free run for you 🌈

😭 ERRORS 😭

okay bestie, sometimes things go sideways and Perl will yell at you. here's the whole drama, error message by error message πŸ’…

  • This Perl not built to support threads β€” so the specific copy of Perl you're trying to use was not built with the useithreads configuration option. like, at all. ngl, that's the whole problem right there 😭

and listen, this isn't a "just add the module" situation. having threads support requires all of Perl and all of the XS modules in the Perl installation to be rebuilt. yep, everything. it is not just a question of adding the threads module (i.e., threaded and non-threaded Perls are binary incompatible). so no, you can't just glue it on. fr fr 🫠

  • Cannot change stack size of an existing thread β€” the stack size of currently extant threads cannot be changed. periodt. so this little number right here:
$thr->set_stack_size($size);

will hand you the above error, every single time. no cap πŸ’€

  • Cannot signal threads without safe signals β€” safe signals must be in effect to use the ->kill() signalling method. that's the rule, bestie. see "Unsafe signals" for more details πŸ”₯
  • Unrecognized signal name: ... β€” the particular copy of Perl you're trying to use does not support the specified signal being used in a ->kill() call. so your vibe check on that signal name did not pass πŸ™ˆ

πŸ› BUGS AND LIMITATIONS πŸ›

okay bestie, before you go off and file a bug report like "this module is broken 😀", pls do the polite thing: check the discussion forum, maybe post there first, and see if what you hit is already a known problem. saves everyone time fr fr πŸ’…

🧡 Thread-safe modules

If you're out here writing modules that might get used in threaded apps β€” especially anything touching non-Perl data or XS code β€” go read "Making your module threadsafe" in perlmod. like, actually read it. it's giving essential ✨

πŸ’€ Using non-thread-safe modules

ngl, you will eventually bump into a Perl module that isn't thread-safe. like, it might straight-up crash the Perl interpreter mid-run, or dump core on termination 😭😭 Depending on the module and what your app actually needs, you might be able to work around it.

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 instead, try reworking your app so the module gets loaded (again with "require" and ->import()) after all your threads are started β€” and in a way where no other threads start afterwards. timing is everything πŸ’…

If none of that works, or it's just not enough for your app? file a bug report on <https://rt.cpan.org/Public/> against the problematic module. not your code's fault, it's theirs 🫢

πŸ“ Memory consumption

on most systems, if you're constantly creating and destroying threads over and over, the Perl interpreter's memory footprint will just keep growing 😭 it's easy to just launch threads and ->join() or ->detach() them, sure β€” but for long-lived applications, you're way better off keeping a pool of threads and reusing them for whatever work comes up, using queues to tell threads there's pending work. the CPAN distribution of this module ships a simple example (examples/pool_reuse.pl) showing 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 current working directory setting is shared between all threads β€” so changing it in one thread (say, with chdir()) affects every thread in the app. yes, all of them. no cap 😳

On MSWin32, each thread keeps its own current working directory setting. different vibes per thread, iykyk.

🌈 Locales

Before Perl 5.28, locales and threads simply could not hang out together, 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 πŸ’–

If you want a thread 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, just do:

POSIX::setlocale(LC_ALL, "");

🌸 Environment variables

Currently, on all platforms except MSWin32, every system call (e.g. using system() or back-ticks) made from threads uses the environment variable settings from the main thread. Translation: changes you make to %ENV in a thread will not show up in system calls made by that thread. rude, honestly πŸ™ˆ

To work around it, set environment variables as part of the system call itself. like this:

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

On MSWin32, each thread maintains its own set of environment variables. main character energy per thread πŸ’…

πŸ”” Catching signals

Signals are caught by the main thread (thread ID = 0) of a script. so if you set up signal handlers in threads for any purpose other than "THREAD SIGNALLING" as documented above, it will not accomplish what you intended. it's giving "I did the work and got no credit" 😭

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. lowkey annoying but that's just how it is πŸ¦‹

⚠️ 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 the full tea β˜•

Safe signals is the default behavior, and the old, immediate, unsafe signalling behavior is only in effect in these 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. seriously. don't. πŸ’€

πŸŽ€ Identity of objects returned from threads

When a value is returned from a thread through a "join" operation, the value and everything it references gets copied across to the joining thread β€” much the same way 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. thorough queen πŸ’…

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. So after joining, the parent will 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. like, be aware bestie 😳

πŸ¦‹ 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. workaround era ✨

πŸ’œ 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).

But here's the thing β€” 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. like, don't do it, I'm begging 🫢

πŸ“‚ 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 check 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 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. messy πŸ’€

If you're 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 β€” join all threads before exiting the program instead. it's the responsible thing to do πŸ’…

🧚 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. no cap, just upgrade 😀

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. πŸ™ˆ

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 πŸ’– (yes, that's the whole requirement. slay.)

πŸ‘€ SEE ALSO πŸ‘€

okay so you're done reading and you want more? iconic behavior, honestly. here's where to go next, bestie:

  • threads on MetaCPAN β€” https://metacpan.org/release/threads β€” literally the whole release, go click around
  • Code repository for CPAN distribution β€” https://github.com/Dual-Life/threads β€” the source source, no cap
  • threads::shared β€” the sibling module, you will need it
  • perlthrtut β€” the tutorial, aka the "explain it like I'm five" doc 🍼

and then the ancient scrolls, aka the classic perl.com articles:

plus more places to lurk:


πŸ’– AUTHOR πŸ’–

  • Artur Bergman <sky AT crucially DOT net>
  • CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>

like, respect the elders, fr fr πŸ™


πŸ“œ LICENSE πŸ“œ

threads is released under the same license as Perl. that's it, that's the whole vibe. go read Perl's license and you're set πŸ’…


πŸŽ€ ACKNOWLEDGEMENTS πŸŽ€

shoutout time, because none of this happens alone:

  • Richard Soderberg <perl AT crystalflame DOT net> β€” helping me out tons, trying to find reasons for races and other weird bugs! (the real MVP of "why is this breaking 😭")
  • Simon Cozens <simon AT brecon DOT co DOT uk> β€” being there to answer zillions of annoying questions (a zillion. that's a real number of questions.)
  • Rocco Caputo <troc AT netrus DOT net> β€” just, legend behavior
  • Vipul Ved Prakash <mail AT vipul DOT net> β€” helping with debugging πŸ”₯
  • Dean Arnold <darnold AT presicient DOT com> β€” stack size API, the reason your threads don't explode 🫢

and that's a wrap on threads(3pm) bestie!! πŸ¦‹ you made it to the end, I'm so proud 😭✨ this page is from the source that calls itself perl v5.42.3, and its date stamp is 2026-11-03 β€” so yes, very futuristic of us. now go forth, spawn some threads, and remember: share your data with threads::shared or the vibes will NOT be immaculate. mwah πŸ’‹πŸŒΈ

πŸ“¦ where this page comes from