dh has asked for the wisdom of the Perl Monks concerning the following question:
Basically, I have an array called @host_array that contains information about the hosts that I want to see whether they are alive or dead. I need to check their current status against their old status and send an alert if something changes. Unfortunately, I can't seem to get the reference right. That means that when I update a value in the $task variable within sub 'pinger', it doesn't actually update the original array; just its local version of the data.
I want to pass a reference to the entire array to run_threaded and then a reference to a slice of that array from run_threaded to pinger.
populateHosts(1); while (1) { run_threaded(10,\&pinger,\@host_array); } sub run_threaded { my ($threads,$func_to_thread, $hosts) = @_; my (%threads); my $n = 0; my $debug = 1; my $m = $threads-1 > $#{$hosts} ? $#{$hosts} : $threads-1; while (1) { last if $n >= $#{$hosts}+1; foreach my $host (@$hosts[$n..$m]) { #Still a reference here! I can change the value of $host[ +x] and it will stick. $threads{$host} = new threads $func_to_thread, $host; } map { $threads{$_}->join if $threads{$_}; } @{$hosts}[$n..$m]; # work out the next range of instances to work on $n = $m == 0 ? 1 : $m+1; $m = $n+$threads-1 < $#{$hosts} ? $n+$threads-1 : $#{$hosts}; } } sub pinger{ $task = shift; # Create pinger $p = Net::Ping->new("tcp"); $p->port_number($task->[4]); if( $p->ping($task->[3], 6) ) { print " PASS: @$task[2] "; $task->[5] = 1; #I want to update @host_array, but it's not a reference! } else { print " FAIL: @$task[2] "; $task->[5] = 0; #I want to update @host_array, but it's not a reference! } $task->[2] .= "-2"; $p->close(); } sub populateHosts { ($init) = @_; # DEFINE A MySQL QUERY $query = "SELECT * FROM `sites`"; # EXECUTE THE QUERY $db->query($query); my $set = $db->create_record_iterator; $i=0; while (my $rec = $set->each) { $host_array[$i][0] = $i; $host_array[$i][1] = $rec->[0]; $host_array[$i][2] = $rec->[1]; $host_array[$i][3] = $rec->[2]; $host_array[$i][4] = $rec->[3]; if ($init) { $host_array[$i][5] = $rec->[4]; $host_array[$i][8] = $rec->[5]; $host_array[$i][6] = 1; $host_array[$i][7] = time; } $i++; } }
There are some lines that I omitted for brevity, but the function should still be similar. Thanks!
By the way, the great thread function 'run_threaded' came from http://greg-techblog.blogspot.com/2009/06/threading-in-perl.html
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Trouble passing an array reference to my threads
by zentara (Cardinal) on Nov 23, 2011 at 10:49 UTC | |
|
Re: Trouble passing an array reference to my threads
by NetWallah (Canon) on Nov 23, 2011 at 06:39 UTC | |
by zwon (Abbot) on Nov 23, 2011 at 12:51 UTC | |
by NetWallah (Canon) on Nov 23, 2011 at 23:41 UTC | |
by zwon (Abbot) on Nov 24, 2011 at 16:11 UTC | |
by dh (Novice) on Nov 23, 2011 at 13:27 UTC |