当其他线程正在等待读取时,写入串口将永远阻塞

Writing to serial-port is blocking forever when other thread is waiting in read

本文关键字:串口 永远 线程 其他 在等待 读取      更新时间:2023-10-16

我编写了一个小程序来测试我的串行类(基于win32 api)。一个线程从串行端口读取并写入标准输出,而另一个线程(main)从标准输入读取并写入串行端口。但是串行端口写入永远是阻塞的。如果我不启动串口读线程,串口写不会阻塞。我在Windows 7上使用visual studio 2008。我怎样才能避免阻塞?

串口打开:

    handle = ::CreateFile(portname,
        GENERIC_READ | GENERIC_WRITE,//access ( read and write)
        0,    //(share) 0:cannot share the COM port                        
        NULL,    //security  (None)                
        OPEN_EXISTING,// creation : open_existing
        0, //FILE_FLAG_OVERLAPPED,
        NULL// no templates file for COM port...
        );

串口写入:

virtual size_t write(const void * buffer, size_t size)
{
    unsigned long bytesWritten;
    if (!WriteFile(handle, buffer, size, &bytesWritten, NULL))
    {
        throw SystemError("Serial::write(): WriteFile() failed");
    }
    return bytesWritten;
}

串口读取(从其他线程调用)

virtual size_t read(void * buffer, size_t max)
{
    unsigned long bytesRead;
    if (!ReadFile(handle, buffer, max, &bytesRead, NULL))
    {
        throw SystemError("Serial::read(): ReadFile() failed");
    }
    return bytesRead;
}

查看此链接是否有帮助

串口上是否有数据要读?我认为对ReadFile的调用是一个阻塞调用,除非有东西要读,否则不会返回。你可以在上面设置TimeOut值,函数会返回,然后你会看到你的写操作继续。

另外,我完全不知道这个API,但是你不应该在多线程上下文中同步访问串行端口吗?

您可能需要查看此链接以获取更多信息:http://msdn.microsoft.com/en-us/library/ms810467.aspx