是否使用重叠 I/O 并不是真正的问题:重叠只是为您的程序腾出一些时间。我写过很多这样的程序,结论总是使用一个线程来处理所有的 COM 例程。该线程调用重叠或同步方法的相关性较低,只要线程空闲执行 WaitForMultipleObjects()。
我编写最近的 COM 终端的方式是这样的(伪):
thread()
{
while not kill the thread event
{
WaitForMultipleObjects (open port, close port, kill the thread event)
if (open port)
{
send();
receive();
wait_for_send_and_receive();
}
}
}
send()
{
take COM_port mutex
if(there is something to send)
{
copy send_data to local_data, protect this with mutex
WriteFileEx(COM_port,
local_data,
size,
some_overlapped_struct_stuff);
handle errors
}
release COM_port mutex
}
receive()
{
take COM_port mutex
ReadFileEx(COM_port, ...);
handle errors
release COM_port mutex
}
wait_for_send_and_receive()
{
WaitForMultipleObjects (open port,
close port,
kill the thread event,
send done event from send callback routine (overlapped I/O),
receive done event from receive callback routine (overlapped I/O)
);
}
当然,这是一种过度简化,因为您需要各种功能来打开/关闭 COM 端口、数据混洗等。可能需要几个 mutice。
如果不是公司财产,我会分享真实的,工作的生产代码:( 4 天似乎有点乐观,从我的项目日志来看,我花了几个月的时间将一个工作的 COM 端口终端开发到生产质量水平。仅 COM 端口驱动程序就大约 1k loc,到处都有很多 Win API 调用。