The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


Threads::Pool - API to get a Pool of reusable threads


        my $pool = Threads::Pool->getInstance( [[NUMBER OF THREADS, SUB CODEREF], WAIT SECONDS] );
     or my $pool = Threads::Pool->getInstance( { [[ code => SUB CODEREF, threads => NUMBER OF THREADS ], wait =>  WAIT SECONDS ] } );
        my $same_pool_as_the_ones_before = Threads::Pool->getInstance( SUB CODEREF );
        $pool->addToTheQueue( \@array );


This class instances a pool of reusable threads, gives them a task, and then adds to a shared queue any $obj you want to give them to evaluate. Your $obj MUST be shareable ( all types but glob & coderef ), or at least serialized, so that you can then deserialize it inside the SUB CODEREF you supplied, and put in an ARRAYREF ( mandatory ) which will be the arg of the ->addToTheQueue() method. You must also supply the number of threads you want to be run inside the pool at creation time. Optionally you can give a wait time for the threads to wait between executions of the coderef, defaults to 0.3 seconds, expressed in integers or floats (absolute values).

You can call the pool's instance from wherever in your code, passing as argument always the same CODEREF, as it's a static member of this class ( say like $pool->getInstance( CODEREF ) ). Once the instance is created, every attempt to recreate it will just be ignored, so you need to destroy it ( via ->destroy() ) before doing it.

The pool can't give you any assurance that all the threads will get their jobs finished before exiting the main program, so you MUST ensure that they'll have enough time to run ( if you care ). It's thus advisable that you destroy() the pool when you're done. Otherwise perl will most probably complain that you still have running threads while exiting ( mostly if you've got more than a pool at once in the same scope, as the reference are statically kept by the class itself, so that no automagic cleanup method will be invoked ), although the pool will do its best to kill them beforehand.

Requires at least Perl 5.8.0 and the support to ithreads, with the presence of the threads and threads::shared modules.


getInstance( [[ SUB CODEREF, NUMBER OF THREADS ], WAIT SECONDS] ) or getInstance( { [[ code =\ SUB CODEREF, threads =\> NUMBER OF THREADS ], wait =\> WAIT SECONDS ] } )>

This method returns the pool's instance, if already created, or creates it with arguments you pass;

addToTheQueue( $obj )

This method lets you add the args you want to be passed to the coderef by the threads. This must be an ARRAYREF to the array containing the args you want to be passed.


This method destroys the pool's instance, waiting for all the threads to have their jobs done.


No support is available


Francesco Serra,

Copyright 2013.