我正在使用此代码,从发出哔哔声的方式开始,一旦程序启动它就不会停止。我怀疑问题出在$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++;
}
}
答案 0 :(得分: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++) {}
}