r1n0 has asked for the wisdom of the Perl Monks concerning the following question:
#!/usr/bin/perl -w use strict; use warnings; use threads; use threads::shared; use Thread::Queue; use IO::Socket; our $alock:shared; our @uri_list:shared; my $Server_IP = "172.168.0.1"; my $Server_IP_tcp_request_port = 40000; #Set up the queue for playing my $Q = Thread::Queue->new(); #Start the thread that keeps the queue full of jobs my $thr1 = threads->create(\&StartJobRequest,1); #Start a thread that checks the queue for jobs #This is only a filler for this code on perlmonks (no provided code fo +r StartPicker is provided, in order to reduce code space) #This code takes queued jobs and performs them, as it completes, it pu +lls from queue for next job. #The actual code has many different Job pickers my $thr2 = threads->create(\&StartPicker, 2); #Join the threads $thr1->join(); $thr2->join(); sub StartPicker{ #Cool stuff goes on here. ;-) } sub StartJobRequest{ my $desired_q_level = 25; my $thid = threads->tid(); #let's start a never ending process for(;;){ my $pending = $Q->pending(); #Check to see if we need to get a task from server. #Only to be done if queue has less than 25 jobs if ( $pending <= $desired_q_level ){ my $collect = $desired_q_level - $pending; for(my $a=0; $a<$pending; $a++){ my $socket = IO::Socket::INET->new( PeerAddr => $Server_IP, PeerPort => $Server_IP_tcp_request_port, Proto => 'tcp', Reuse => 1, ) or warn "Can not open socket for client to $Serv +er_IP on port $Server_IP_tcp_request_port\nReason: $!\n\n"; if ($@ ){ #Set $a to exit loop after this $a=$collect; my $warn_sleep = int rand 10; print "Can not connect to server $Server_IP on por +t $Server_IP_tcp_request_port\nSleeping for $warn_sleep seconds\n"; } else{ my $payload = "Need_Job"; $socket->autoflush(1); print $socket $payload; my $line = <$socket>; if ($line =~ /^JOB:/){ $line=~ s/\n//; write_log_entry("Job received: $line\n"); lock($alock); $Q->enqueue($line); } elsif( $line=~ /=EMPTY=/){ #set $a to exit loop after this $a=$collect; sleep(3); } else{ print "Unknown returned info from Server: $lin +e\n"; #set $a to end loop $a=$collect; } } close($socket); } } } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Monitoring Threads and keeping them alive/reviving them
by bot403 (Beadle) on Oct 22, 2009 at 19:50 UTC |