0

我正在玩这段代码,从哔哔声的方式来看,一旦程序启动它就不会停止。我怀疑问题出在$thread->kill('KILL')->detach;.

有任何想法吗?还是我做错了什么?

#!c:/perl/bin/perl

use threads;
use Audio::Beep;

my $thread;
my $playing=0;

while (1) {
  my $val = int( rand(10) );
  print "$val\n";

  # if event "start" occurs and is not playing create thread
  #if ( ($val==0 || $val==1 || $val==2 || $val==3 || $val==4 ) && (!$playing) ) {
  if ( ($val==0 || $val==1 || $val==2 ) && (!$playing)  ) {
    $playing = 1;
    $thread = threads->create( 
      sub {
        local $SIG{'KILL'} = sub { threads->exit() };
        print "start beep\n";
        beep( 520, 10000 );
      } 
    );
  }
  # if event "end" occurs and playing wait 1 seconf and kill thread
  elsif ( ($val==5 ) && $playing ) {
    print "stop beep \n";
    #sleep(1);  
    $playing = 0;
    $thread->kill('KILL')->detach;
  }

  #sleep(1);

  $count = 0;
  for($i=0; $i<99999 ; $i++) {
     $count++;
  }
}
4

1 回答 1

0

我认为您的程序主要按您的意愿运行。我现在看到的问题之一是每一次哔哔声听起来都很相似。我重新写了一点,给哔哔声一些质感,并放慢速度,这样你就可以欣赏正在发生的事情。

此外,正如您所写的那样,线程有可能会在您杀死它之前自行结束。我已经使线程持久化,并添加了额外的诊断信息,这些信息将确认线程何时运行以及何时不运行。

use strict;
use warnings;
use threads;
use Audio::Beep;

my $thread;
my $playing=0;

while (1) {
  my $val = int( rand(30) );
  print "$val\n";
  my $running = threads->list(threads::running);
  print "Threads running: $running\n";

  # if event "start" occurs and is not playing create thread
  if ( ( $val==1 ) && (!$playing)  ) {
    $playing = 1;
    print ">>>>>>>>\n";
    sleep(1);
    $thread = threads->create( 
      sub {
        local $SIG{'KILL'} = sub { threads->exit() };
        print "start beep\n";
        while (1) {
          beep( 520, 100 );
          sleep(1);
          beep( 3800, 100 );
          sleep(1);
          beep( 2000, 100);
          sleep(1);
        }
      } 
    );
  }
  # if event "end" occurs and playing wait 5 seconds and kill thread
  elsif ( ($val==2 ) && $playing ) {
    print "STOPSTOPSSTOPSTOPSTOP\n";
    sleep(5);  
    $thread->kill('KILL')->detach;
    $playing = 0;
  }

  for(my $i=0; $i<999999 ; $i++) {}
}
于 2014-01-01T19:22:42.190 回答