当其他线程正在等待读取时,写入串口将永远阻塞
Writing to serial-port is blocking forever when other thread is waiting in read
我编写了一个小程序来测试我的串行类(基于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
相关文章:
- 为什么我要从串口读取垃圾?
- Boost Asio SerialPort。无法创建并打开串口服务
- 如何在QtWidget中使用c++串口发送数据
- 如何插入十六进制值并发送到串口?
- 串口打开返回 EAGAIN
- QT 5.10.1 串口不发送,为什么?
- 通过串口发送后无法获取原始值
- C++ / RS232C 串口 / 事件回调异步读取缓冲区 / 不使用线程
- 串口读取功能的通信超时和线程不超时
- QT 5.7 串口读取速度很慢
- 串口通信
- 为什么Qt(4.8)串口(qextserialport)分两部分从设备读取数据
- 将C++串口奇偶校验更改代码从 Linux 移植到 Windows
- qt串口未打开
- 有没有一个跨平台的c++串口库可以枚举端口
- Qt串口,当我写的时候,我看不懂我写的东西
- 是否可以检查串口是空闲还是占用
- 无法将简单的读/写串口代码从 boost::asio::serial_port 迁移到 QSerialPort
- 通过c++中的串口发送数据
- 当其他线程正在等待读取时,写入串口将永远阻塞