This opens a file, starts 4 threads; writes to that file from all 4 threads (with locking) at random for a short while then stops the threads. It then reopens the file and prints it to stdout:
#! perl -slw use strict; use Time::HiRes qw[ time sleep ]; use threads; use threads::shared; our $THREADS ||= 4; my $sem :shared; open LOG, '>', 'log.txt' or die $!; sub logit { lock $sem; return printf LOG @_; } sub thread { my $tid = threads->self->tid; my $stop = shift; warn $tid, ": starting:", time(), " Stoptime: $stop\n"; while( sleep( rand( 1 ) ) && time() < $stop ) { logit "%2d: The time is %f\n", $tid, time; } warn $tid, ": stopping at ", time(), "\n"; } my @threads = map threads->create( \&thread, time() + int( rand 10 ) ), 1 .. $THREADS; warn "threads started; waiting\n"; $_->join for @threads; warn "threads done\n"; open LOG, '<', 'log.txt' or die $!; print while <LOG>; close LOG;
What more do you need?
In reply to Re: [threads] Open a file in one thread and allow others to write to it
by BrowserUk
in thread [threads] Open a file in one thread and allow others to write to it
by Gangabass
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |