我制作了一个小程序来测试我的串行类(基于win32 api)。一个线程从串口读取并写入标准输出,而另一个线程(主线程)从stdin读取并写入串口。但是串口的书写永远是阻塞的。如果我不启动串口读取线程,串口写入就不会阻塞.我在Windows 7上使用Visual 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;
}发布于 2014-08-03 01:21:25
检查一下这个link,看看它是否有用。
是否有任何数据可在串口上读取?我认为对ReadFile的调用是一个阻塞调用,除非有什么可读的,否则不会返回。您可以在其上设置TimeOut值,函数将返回,然后将看到您的写操作继续。
而且,我并不完全了解这个API,但是您不应该在多线程上下文中同步访问串行端口吗?
您可能希望查看此链接以获得更多信息:http://msdn.microsoft.com/en-us/library/ms810467.aspx
https://stackoverflow.com/questions/25100736
复制相似问题