【发布时间】:2016-07-19 07:38:33
【问题描述】:
我在 Perl 线程中使用串行端口,我可以在线程中读写。但是如果我想关闭串行端口以便另一个应用程序可以使用该端口并稍后再次打开它,我就无法再读写了。该怎么做?
my $dev;
my $port = "/dev/ttyACM0";
my $run :shared = 0;
my $thr;
my $read_thr;
sub port_init
{
$dev = Device::SerialPort->new($port, 1) || die "Cannot open $port: $!\n";
$dev->baudrate(115200);
...
$run = 1;
}
sub read_port # read async
{
my $str;
while ($run == 1)
{
$str = $dev->lookfor;
if ($str ne "")
{
print "recv: $str\n";
}
sleep 0.5;
}
}
sub write_port
{
my $msg = shift;
if ($run == 1)
{
$dev->write($msg."\r");
}
}
sub close_port
{
$run = 0;
$dev->close;
}
# Main
port_init();
$read_thr = threads->new(\&read_port);
$read_thr->detach();
if ("event1 occurs") # send cmd to port
{
$thr = threads->new(\&write_port, "ATI"); # works, response received
$thr->detach();
}
if ("event2 occurs") # another application is requesting the port
{
$thr = threads->new(\&close_port);
$thr->detach();
# wait till application has finished
port_init();
$read_thr = threads->new(\&read_port);
$read_thr->detach();
# send cmd to port, doesn't work
$thr = threads->new(\&write_port, "ATI");
$thr->detach();
}
关闭端口后,我不能再使用它了。 read_port 在第二次启动后在 Device::SerialPort::input 中引发错误 #9。我需要线程,因为解析器必须始终可以访问。
【问题讨论】:
标签: multithreading perl