sub worker { my( $Q ) = shift: while( my $workItem = $Q->dequeue ) { ## Perform query ## Perform comparison ## Perform output/cleanup } } #### ## in the main thread: my $outputMutex : shared; ... open OUTFILE, '>', ... ## In the worker threads ... { lock $outputMutex; print OUTFILE ... }