in reply to Progress bar with (i)threads

The problem with the script exiting while there are still threads running is one of timing. The main thread exits before the progressBar has had a chance to finish sleeping for 10 and check $keepRunningProgressBar.

The problem with the lack of output is almost definitely a buffering issue. Try making the request using wget or with telnetand see exactly what is being returned.

This code demonstrates that the logic works, and it outputs a dot every 10 seconds, but only forces the user to wait a maximum of one second more than the process would have taken anyway:

#!/usr/bin/perl use strict; use warnings; use threads; use threads::shared; # set a shared value of TRUE for running the progress bar my $keepRunningProgressBar : shared = 1; # Set the progress bar running indefinitely my $progressBar = threads->create( sub { my $i = 0; while ($keepRunningProgressBar == 1) { if ($i++ % 10 == 0) { print ".\n"; } sleep(1); } } ); # Now do stuff in the work thread my $threadForSpidering = threads->new( sub { my $i = 0; while ($i++<5) { print "Working\n"; sleep 1; }}); #The work thread finished $threadForSpidering->join; #And tells the progress bar to stop running $keepRunningProgressBar = 0; $progressBar->join; print "\nGOT HERE\n";
UPDATE I have never used threads before, but I see that the version of threads.pm that came with my perl is old 1.07, and with the current version you could do something like this:

#!/usr/bin/perl use strict; use warnings; use threads; use threads::shared; # set a shared value of TRUE for running the progress bar my $keepRunningProgressBar : shared = 1; # Set the progress bar running indefinitely my $progressBar = threads->create( sub { while ($keepRunningProgressBar == 1) { print ".\n"; sleep(10); } ); # Now do stuff in the work thread # Now do stuff in the work thread my $threadForSpidering = threads->new( sub { my $i = 0; while ($i++<5) { print "Working\n"; sleep 1; }}); #The work thread finished $threadForSpidering->join; #And tells the progress bar to stop running $keepRunningProgressBar = 0; $progressBar->kill('KILL')->detach(); print "\nGOT HERE\n";

Replies are listed 'Best First'.
Re^2: Progress bar with (i)threads
by PockMonk (Beadle) on Dec 08, 2006 at 14:33 UTC
    Thank you. You are of course right about the timing. That's very simple, I should have seen that. No warnings now when the main thread exits. Thanks!