Threads#

Perl 5’s headline concurrency story is interpreter threadsithreads for short — supplied by the core threads and threads::shared modules. Each ithread is a separate Perl interpreter running inside the same OS process, with its own pad, its own lexicals, and a copy of every package variable captured at spawn time. Data is shared between threads only when you opt in by attaching :shared to it.

This chapter teaches that model. The idiom, the vocabulary, and the pitfalls are the ones every Perl programmer who has touched concurrency has encountered, and you need to recognise them when reading existing Perl code.

pperl status — read this first#

pperl does not implement ithreads. The threads and threads::shared modules are not available. At runtime:

  • use threads fails at compile time.

  • use threads::shared fails at compile time.

  • The lock built-in is a silent no-op, exactly as upstream Perl behaves when built without thread support. Code that sprinkles lock defensively for single-threaded compatibility runs unchanged.

That decision is deliberate. ithreads impose a per-interpreter data copy, constrain every core module’s internals, and historically bred a long tail of subtle bugs around shared aggregates, signal delivery, and library thread-safety. pperl invests instead in runtime-level parallelism for pure Perl code — JIT-compiled loop bodies dispatched across a Rayon work-stealing pool, with automatic reduction analysis and zero user-visible thread objects. See Parallel Execution for how that works and when it fires.

If you are porting an existing ithreaded program to pperl, read Alternatives to ithreads for the shapes that map cleanly — almost every threads-based program falls into one of three patterns, each with a simpler and faster pperl equivalent.

How this chapter is organised#

  • ithreads basics — the perl5 model: spawning with threads->create, joining and detaching, passing parameters, returning values, the three structural patterns (boss/worker, work-crew, pipeline).

  • Shared datathreads::shared, the :shared attribute, lock, semaphores, queues, race conditions, deadlocks. Every section flags pperl’s divergence.

  • Alternatives — pperl’s auto-parallelisation, fork-based concurrency with fork, and a decision table for picking the right tool.