是否使用重疊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端口的各種功能,洗牌的數據等。可能需要幾個重點。
如果不是公司財產,我會分享真實的工作生產代碼:(4天似乎有點樂觀,從我的項目日誌來看,我花了幾個月的時間開發出一個可用的COM端口終端質量水平,單獨的COM端口驅動程序大約是1k loc,並且有很多Win API調用全部結束
非常感謝你的快速回答,我只需要一些東西來傳送幾千字節的數據(圖片)可能還有一些命令 我認爲,我必須保持這個儘可能簡單,並建立一個只接收數據的模式,我不能打任何東西(它應該是遠程控制的) 它是作爲暑期學校項目的一部分,我告訴我的顧問,這個建設一個終端是太多的工作,但是... 無論如何,非常感謝你,這證實我相信這是「頂一下」。 – 2012-08-10 10:09:26
@JayEfGee如果你的程序除了串行通信以外沒有其他的工作,這個項目就容易多了,因爲你可能沒有線程或者重疊的I/O。 – Lundin 2012-08-10 10:42:29