1

我在 perl (5.12 ActiveState) 中使用线程来允许在 Windows 上的两个不同 COM 端口上进行并行和异步写入。这就是我的代码的样子:

#!/usr/bin/perl

use warnings;
use strict;
use Win32::SerialPort;
use threads;

my $ComPortObj = new Win32::SerialPort ("COM10") or die ("This is the bitter end...");
[... omit port settings ...]

my $ComPortObj2 = new Win32::SerialPort ("COM6") or die ("This is the bitter end...");
[... omit port settings ...]    

my $s_read = "";

my $HangupThr = async 
{
    # printf("THREAD - Wait 3 seconds\n");
    # sleep(3);
    print("THREAD - write on COM10: AT\n");
    $ComPortObj->write("AT\r") || die ("Unable to send command\n");
    printf("THREAD - Wait 1 second\n");
    sleep(1);
    $s_read = $ComPortObj2->input;
    # $s_read =~ s/\n/N/g;
    # $s_read =~ s/\r/R/g;
    print("THREAD - read from COM6: $s_read\n");
    return 1;

};
$HangupThr->detach();

# printf("MAIN - Wait 4 seconds\n");
# sleep(4);
print("MAIN - write on COM6: AT\n");
$ComPortObj2->write("AT\r") || die ("Unable to send command\n");
printf("MAIN - Wait 1 second\n");
sleep(1);
$s_read = $ComPortObj->input;
# $s_read =~ s/\n/N/g;
# $s_read =~ s/\r/R/g;
print("MAIN - read from COM10: $s_read\n");

$ComPortObj->close();
$ComPortObj2->close();

我得到的是程序退出时的错误。完整的输出:

MAIN - write on COM6: AT
THREAD - write on COM10: AT
MAIN - Wait 1 second
THREAD - Wait 1 second
MAIN - read from COM10: AT
OK

THREAD - read from COM6: AT
OK

Error in PurgeComm at C:\userdata\Perl scripts\src\handler_error.pl line 0 thread 1
The operation completed successfully.
Error in GetCommTimeouts at C:\userdata\Perl scripts\src\handler_error.pl line 0 thread 1
Error Closing handle 184 for \\.\COM6
The handle is invalid.
Error closing Read Event handle 188 for \\.\COM6
The handle is invalid.
Error closing Write Event handle 192 for \\.\COM6
The handle is invalid.
Error in PurgeComm at C:\userdata\Perl scripts\src\handler_error.pl line 0 thread 1
The handle is invalid.
Error in GetCommTimeouts at C:\userdata\Perl scripts\src\handler_error.pl line 0 thread 1
Error Closing handle 144 for \\.\COM10
The handle is invalid.
Error closing Read Event handle 148 for \\.\COM10
The handle is invalid.
Error closing Write Event handle 180 for \\.\COM10
The handle is invalid.

这与串行端口处理程序清除有关,我不知道 perl 如何在线程中重复。我在线程中尝试了各种密切尝试,主要......但没有成功。此外,我必须在主程序和线程中使用相同的端口。有什么建议可以防止这些错误吗?

非常感谢!

4

1 回答 1

0

您正在处理串行端口,并且在任何时候只有一个进程可以控制串行端口(某些终端交换机提供多次登录,但您的情况并非如此)在 Windows 中,当一个进程连接到 COM 时,它会自动断开其他进程。您可以通过尝试从 Windows 机器两次登录到相同的 COM 端口来尝试此操作,并且另一个端口应该断开连接,这会导致您看到的无效句柄错误。

您可以尝试的其他事情

  1. 在线程内创建 Com 对象,使用它并在其他线程上访问它之前销毁该对象
于 2013-04-10T16:45:30.860 回答