in reply to [threads] Open a file in one thread and allow others to write to it
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: [threads] Open a file in one thread and allow others to write to it
by Gangabass (Vicar) on Nov 16, 2009 at 13:13 UTC | |
|
Re^2: [threads] Open a file in one thread and allow others to write to it
by gulden (Monk) on Nov 16, 2009 at 12:51 UTC | |
by BrowserUk (Patriarch) on Nov 16, 2009 at 12:58 UTC | |
by gulden (Monk) on Nov 16, 2009 at 13:14 UTC | |
by BrowserUk (Patriarch) on Nov 16, 2009 at 13:23 UTC | |
by gulden (Monk) on Nov 16, 2009 at 13:37 UTC | |
|