繁体   English   中英

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

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

我做了一个小程序来测试我的串行类(基于win32 api)。 一个线程正在从串行端口读取并写入stdout,而另一个线程(主线程)正在从stdin读取并写入串行端口。 但是串行端口写入将永远受阻。 如果我不启动串行端口读取线程,则串行端口写入不会阻塞。 我在Windows 7上使用Visual Studio2008。如何避免阻塞?

串口打开:

    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/zh-cn/library/ms810467.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM