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

标签 c++ windows multithreading visual-c++ serial-port

我做了一个小程序来测试我的串行类(基于win32 api)。一个线程正在从串行端口读取并写入标准输出,而另一个线程(主线程)正在从标准输入读取并写入串行端口。但是串行端口写入永远阻塞。如果我不启动串口读线程,串口写就不会阻塞。我在 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;
}

最佳答案

检查这个 link看看是否有帮助。

串口上是否有需要读取的数据?我认为对 ReadFile 的调用是阻塞调用,除非有可读内容,否则不会返回。 您可以在其上设置 TimeOut 值,该函数将返回,然后您将看到您的写入操作继续进行。

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

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

关于c++ - 当其他线程正在等待读取时,写入串行端口将永远阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25100736/

相关文章:

c++ - 模板特化或函数重载

python - 从 Cygwin 启动 python IDLE 时 Tkinter 中的 tcl_error

c++ - 如何将 hwnd 类型数据存储到平面文件中并将其返回到 hwnd 类型变量中?

c - 在Linux中使用管道在2个线程中增加全局变量替代方案

java - 用Java编写线程

c++ - Boost/C++ eval_if 失败

c++ - 分离线程中的竞争条件

c++ - 以编程方式检查我的机器是否可以访问互联网

java - 无法从 netbeans 运行 tomcat 7

c++ - 产生线程时死锁?