Here is a piece of code that experiment multithreading.
When I push a button _StartThread() function is executed.
After the first push the first thread is launched and it writes a line every second with “1>1” at the end of the line.
After the second push the second thread is launched and it writes lines with “2>2” at the end.
I see the program keep writing a line with “1>1” and then a line with “2>2” at the end, and I suppose that I use synchronization by WaitForSingleObject(),ResetEvent() and SetEvent() in a proper way.
But after some lines the program mix the figures at the end of the message and I get “1>2” and “2>1”, and I begin to think that I don’t use the synchronization function in a proper way. It is true?
LONG CTestMsgDlg::m_nWorking = 0;
HANDLE CTestMsgDlg::m_hevent;
CTestMsgDlg::CTestMsgDlg(CWnd* pParent )
: CDialog(CTestMsgDlg::IDD, pParent)
{
m_hevent=CreateEvent(NULL,TRUE,TRUE,_T("hevenim")); }
void CTestMsgDlg::_StartThread()
{
CWinThread* pThread;
m_nWorking+=1;
pThread = AfxBeginThread(&CTestMsgDlg::WorkerThread, m_hWnd, THREAD_PRIORITY_NORMAL);
}
UINT AFX_CDECL CTestMsgDlg::WorkerThread(LPVOID lpParam)
{
int v2 = m_nWorking;
int v4;
long v5;
DWORD rwait;
BOOL eventset;
while(m_nWorking)
{
CString* pString = new CString;
DWORD dwThreadID = ::GetCurrentThreadId();
SYSTEMTIME st = {0};
::GetLocalTime(&st);
rwait=WaitForSingleObject(m_hevent,9999);
eventset=ResetEvent(m_hevent);
if (!eventset) return 0;
v9=v2;
for (v4=1; v4<222222222; v4++) v5=v4*v4/(v4+1) ;
pString->Format(_T("Posted by thread %X at %02u:%02u:%02u:%03u %02d >%X"),
dwThreadID, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, v9, v2);
eventset=SetEvent(m_hevent);
if (!eventset) return 0;
::PostMessage((HWND)lpParam, WM_APP_TIMESTAMP, 0, (LPARAM)pString);
}
return 0;
}