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.
Roman

Update

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

In reply to [threads] Open a file in one thread and allow others to write to it by Gangabass

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.