我做了一个小程序来测试我的串行类(基于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/