use threads; use Thread::Queue; ... my $Q = new Thread::Queue; sub logmsg { // added thread id to messages. $Q->enqueue( threads->tid . ": @_"; ); } async { open my $log, '>', 'logfile' or die $!; while( $Q->dequeue ) { my $now = time; my $msec = int( ( $now - int($now) ) * 1000 ); my ( $sec, $min, $hour ) = localtime(time); sprintf $log "%02d:%02d:%02d:%03d %s\r\n", $hour, $min, $sec, $msec, $_; } close $log; } ... logmsg( ... ); ... $Q->enqueue( undef ); // to terminate logging thread.