Listing 4.
COUNTERPOINT
Tom Christiansen
Threads
The Perl Journal, Summer 1998
 

Programming with multiple threads of control is old hat for multitasking systems like Unix. In Perl, as in C, process creation has traditionally used fork() to clone duplicates of the current process. Because making new tasks quickly is critical to any multitasking system, significant effort has gone into streamlining this call, rendering fork() as efficient as it is elegant. Unlike lightweight processes (threads), any data shared across a fork() must be explicitly shared, thus deftly avoiding the concurrent access and locking issues that so plague thread-based programming. Copy-on-write technology keeps this cheap. A thread's join() operation corresponds to waitpid() for processes, and communication between related processes uses pipes as data queues. While some programs are easier to write using threads, this is not universally true - and threads carry their own perils, being trickier than you might think. Often forks and threads can implement the same program: see the prime-fork.gz and prime-thread.gz programs at: http://www.perl.com/CPAN/authors/id/TOMC/scripts/ for parallel implementations. There is also a fwdport.gz program, which forks twin processes per client connection for a simple implementation of bidirectional I/O.