Nice catch Scott, I didn't even realize the same structure was being passed
to both thread. :-x
AliR.
kathy wrote:
I have a piece of code:
...
m_data.sThreadType = _T("Client1");
CWinThread* clientThread1 =
AfxBeginThread(ClientThreadFunction,(LPVOID)&m_data);
::Sleep(1);
m_data.sThreadType = _T("Client2");
CWinThread* clientThread2 =
AfxBeginThread(ClientThreadFunction,(LPVOID)&m_data);
...
UINT CDialog_MFC_WorkThread::ClientThreadFunction(LPVOID pParam)
{
ThreadData* pData = (ThreadData*) pParam;
CString cs = pData->sThreadType;
if(cs == _T("Client1"))
m_CListBox_Client1.AddString(_T("in ClientThreadFunction()"));
else if(cs == _T("Client2"))
m_CListBox_Client2.AddString(_T("in ClientThreadFunction()"));
return 0;
}
it runs OK.
If it runs OK that is due to sheer luck. The time at which each thread
looks at the string is not predictable or even repeatable. For example,
thread 1 might see the "Client1" or the "Client2" string or, even worse,
it might look at the string while it is being changed. You must use
synchronization to access data that could be changed by one thread while
another thread is reading it. Even better, create a different
ThreadData object for each thread and do not change it while the thread
is running.
Then you need to learn about the MFC limitations on accessing windows
from a thread that did not create them. Basically, don't do that. You
can start here: http://www.flounder.com/workerthreads.htm
--
Scott McPhillips [VC++ MVP]