c++ - "Writefile" for RS232 communication using MFC hangs forever, but -
i maintaining mfc program can send data computer computer b through rs232. transmits data smoothly, hangs forever. there 2 threads sending same data com port in sequence. first thread sends data successfully, second thread hangs @ code "writefile". when second thread on computer hangs @ "writefile", send meaningless data "1" computer b computer a. hanging @ "writefile" on computer stop hanging, , computer b see data sent second thread on computer a.
here rs232 log computer b .
the picture shows 2 threads on computer initiate there own test , send messages computer b. each thread complete there own test , send test_done computer b @ same time. computer b see test_done sent first thread on computer a(the second thread hanging @ writefile @ point.) until manually send "1" computer computer b.
here code sending message computer computer b. length of cmd 255.
bool serialport::autohandlerres(unsigned char* cmd){ while(wait_transfer.islocked()) sleep(1000); wait_transfer.lock(); cstring out; bool retb; uchar endchar[2]={0x0d,0x0a}; out=cstring(cmd); dword num = out.getlength()+2; cmd[num-2]=endchar[0]; cmd[num-1]=endchar[1]; retb=writefile(this->m_hcom, cmd, num, &num, null); sleep(1000); wait_transfer.unlock(); return retb;}
my question possible cause causing thread b hanging @ "writefile"? why hanging not happen on thread a? thank you!
from the msdn page serial communications :
if 1 thread blocked waiting i/o operation complete, other threads subsequently call communications api blocked until original operation completes. instance, if 1 thread waiting readfile function return, other thread issued writefile function blocked.
you issue blocking readfile
prevent writefile
completing. in case race condition between threads ; writes complete before read called, not always.
the best way prevent not call readfile
carelessly, instead wrap in same lock writes, , wait on receive comm event before reading. raw win32 calls setcommmask
, waitcommevent
. can use clearcommerror
detect how many bytes should read (because receive event doesn't tell how data received).
you can use overlapped io allow simultaneous io. find cleaner, it's not simpler.
Comments
Post a Comment