Chapter 40. Threads

Support for threads needs to be built into the Perl executable.

The pragma threads implements thread objects and the necessary operations for threads:

async block

Starts a thread to execute the block. Returns the thread object.


Returns a list of joinable threads.

threads->new(sub [ , args ])

Creates a new thread that starts executing in the referenced subroutine. The args are passed to this subroutine. Returns the thread object.


Returns an object representing the current thread.


The current thread gives up the CPU in favor of other threads.

thread objects support the following methods:


Detaches a thread so it runs independently.

equal (thread)

Returns true if the thread and thread are the same thread. You can also compare thread objects directly, using the == operator.


Waits for the thread to complete. The value returned is the return value from the thread’s subroutine.


Returns the thread id of a thread.

The pragma threads::shared implements operations that enable variable sharing across threads:

cond_broadcast variable

Unblocks all threads waiting for this variable. variable must be locked.

cond_signal variable

Unblocks one thread that is waiting for this variable. variable must be locked.

cond_wait variable

Waits for another thread to issue a cond_signal or cond_broadcast on the variable. variable must be locked and will be temporarily unlocked while waiting.

lock variable

Locks a shared variable against concurrent access. The ...

Get Perl Pocket Reference, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.