I don't understand the logic of the 'if' in the 'foreach' loop. All you really need is:
foreach my $id (0..3) {
# You don't need the 'my $thr =' construct here
threads->create(\&output, $id, 30, $id, $fh);
}
foreach my $thr (threads->list()) {
$thr->join();
}
The threads don't see the 'foreach' loop (i.e., this is not the same as using 'fork'). All they execute is what is inside the 'output' function.