## Shared the array of select ids my @id :shared; ## Select them while (my $rec = $sth->fetchrow_hashref) { push @id, $rec->{unique_id} if desired_rec($rec); } ## Set the number of threads--start with 1 per core our $T //= 4; ## break up the array into non-overlapping ranges my( $step, $s, @ranges ) = ( int @id / $T, 0 ); push( @ranges, [ $s, $s + $step -1 ] ), $s += $step for 1 ..$T; $ranges[ -1][1] = scalar @id; my @threads; ## Loop over those ranges for my $range ( @ranges ) { ##starting a new thread for each push @threads, async { ## Create a new handle in each thread my $dbh = DBI->connect( ... ) or die ..; my $del_sth = $dbh->prepare("DELETE FROM TBL WHERE unique_id = ?"); ## process the subrange one at a time for( @id[ @$range ] ) { eval { $del_sth->execute($_); }; $logger->write("Failed to remove '$_'") if $@; } ## till done $dbh->disconnect; }; } ## Wait for them $_->join for @threads;