【问题标题】:Linux Perl Threads SerialPort close and open againLinux Perl 线程 SerialPort 关闭并再次打开
【发布时间】: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


    【解决方案1】:

    好吧,没有你发布你的实际代码 - 很难说。

    但是我认为问题将是因为您在线程启动之前创建$dev - 并使用port_init() 实例化它 - 但随后每个线程都继承了一个 clone这个对象,当他们开始。

    这会让你处于一个非常混乱的状态——我强烈建议不要首先进入这个状态。因为每个线程仍在运行 - 它是活动的,但已分离 - 所以将“持有”它自己的端口文件句柄实例。

    这非常混乱,几乎可以肯定这就是它无法正常工作的原因。

    我建议你一开始就不要陷入这种情况——不要共享这样的端口,只需要一个线程来处理整个事情。如果您需要比 IPC 共享变量更复杂的东西,请使用 Thread::Queue

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 2023-04-03
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多