in reply to Should I use threads? Perl/DHCP/Radius
#!/usr/bin/perl use warnings; use strict; use threads; use threads::shared; use Glib; use Glib qw/TRUE FALSE/; use Term::ReadKey; $|++; ReadMode('cbreak'); #use Gtk2 qw/-init -threads-init/; print "pid-> ",$$,"\n"; #Glib::Object->set_threadsafe (TRUE); #setup shared hash my %threads; my $count = 0; my $main_loop = Glib::MainLoop->new; Glib::Idle->add( sub{ my $char; if (defined ($char = ReadKey(0)) ) { #print "$char->", ord($char),"\n"; #process key presses here if($char eq 'c'){ $count++; print "count $count\n"; share $threads{$count}{'data'}; share $threads{$count}{'die'}; share $threads{$count}{'thread'}; $threads{$count}{'data'} = 0; $threads{$count}{'die'} = 0; $threads{$count}{'thread'} = threads->new(\&start_thread +,$count)->detach; } if($char eq 'x'){ #my $kill = shift @actives; my $kill = 1; if(defined $kill){ $threads{$kill}{'die'} = 1; print "thread $kill killed\n"; $threads{$kill}{'thread'} = undef; }else{print "no threads running\n";} } return TRUE; #keep this going } }); $main_loop->run; ReadMode('normal'); # restore normal tty settings sub start_thread { my $num = shift; my $self = threads->self; print "Thread ", $self->tid, " started\n"; print "idenitifier: $num\n"; while(1){ if( $threads{$num}{'die'} == 1){print "$num dying\n";return} else{ print ' ' x $num, $threads{$num}{'data'}++,"\n"; select(undef,undef,undef,.5); }; } }
|
|---|