You may not have thread-safe code in serial.Read or serial.Write
stripMsg and packMsg may also have issues.
I don't see any issues which would be causing crashes here, but that doesn't mean there are some other bad things.
You should use
events[
^] instead of CPU hungry loops (at the top of SendThread).
unsigned long ReceiveThread(CMyTabs* myTab)
{
while(true)
{
if(!initialisePort)
{
initialisePort = true;
}
DWORD dwBytesRead = 0;
byte abBuffer[256];
bool crcCheck = false;
bool msgCheck = false;
MsgBlk *msgBlk = new MsgBlk();
do
{
crcCheck = msgBlk->fValidCRC;
msgCheck = msgBlk->fValid;
serial.Read(abBuffer, 256, &dwBytesRead, 0, INFINITE);
if(dwBytesRead > 0)
{
myTab->stripMsg(abBuffer, sizeof(abBuffer), msgBlk);
}
Sleep(50); }while(!msgCheck && !crcCheck);
char szTimestamp[128];
SYSTEMTIME st;
GetLocalTime(&st);
sprintf_s(szTimestamp, 128, "%02d:%02d:%02d:%03d", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
byte bytetobesent[256];
memcpy(bytetobesent, msgBlk->msg, sizeof(bytetobesent));
PostMessage(myTab->GetSafeHwnd(), WM_MSG_RECV, (WPARAM)bytetobesent, (LPARAM)szTimestamp);
delete msgBlk;
}
return 0;
}
unsigned long SendThread(CMyTabs* myTab)
{
while(true)
{
WaitForSingleObject(hMyEvent, INFINITE);
++sendCounter;
sendMsgFlag = false;
DWORD dwBytesWritten=0;
int in_len;
int out_len;
int oplen;
byte inbuf[5];
byte outbuf[512];
inbuf[0] = 0x06;
inbuf[1] = 0x33;
inbuf[2] = sendCounter;
inbuf[3] = (sendCounter >> 8);
inbuf[4] = 112;
out_len = in_len = 5;
oplen = myTab->packMsg(inbuf, in_len, outbuf, out_len);
long Lerror = serial.Write(outbuf, oplen);
if(Lerror != ERROR_SUCCESS)
{
AfxMessageBox(_T("Unable to write to COM Port!"));
}
}
return 0;
}