use strict; use warnings; use threads; use Thread::Queue; use IO::File; my $q = Thread::Queue->new(); sub worker { my $counter = 1; my $number_of_lines = 0; open my $fh, ">", "log" . $counter++ . ".txt" or die $!; $fh->autoflush(1); while (1) { my $thread_id = $q->dequeue(); if ( $number_of_lines >= 20 ) { close $fh; open $fh, ">", "log" . $counter++ . ".txt" or die $!; $fh->autoflush(1); $number_of_lines = 0; } print $fh "This is a very long string containing $thread_id\n"; $number_of_lines++; } } threads->new( \&worker )->detach(); my @threads; foreach my $thread_id ( 0 .. 10 - 1 ) { my $thread = threads->create( 'start_thread', $thread_id ); push @threads, $thread; } foreach my $thread (@threads) { $thread->join(); } sub start_thread { my ( $thread_id ) = @_; while (1) { $q->enqueue($thread_id); sleep 1; } }