Gangabass has asked for the wisdom of the Perl Monks concerning the following question:

Hi, Monks.

First of all i have read Threads: How to share a FileHandle to Write and Threading and File Handles. But i'm still don't know how to make this task:

Sharing file handle is impossible so i try to write to shared variable. But this doesn't work too (it just create ugly file name \$shared_variable).

How i can do that? Now i'm thinking about one writing thread which will communicate with others and write data to log file and create new one. Can you give me hint how i can do this?



Thanks to all. Your suggestions really help. I'm using this code right now:

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; } }