I am creating 5 thread here using ThrdFunc. Here each thread update the listBox.
I was expecting message in this way. Initially come in this way but after some time
Thread1:Adding msg
Thread2:Adding msg
Thread3:Adding msg
But after some time I get message like
Thread0:Adding msg
Thread18967654:Adding msg
Thread18967654:Adding msg
Thread18967654:Adding msg
This is the code:
for (int i = 0;i<6;i++)
{
nThreadNo = i+1;
hWndProducer[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ProducerThrdFunc,(void*)&nThreadNo,0,&dwProducerThreadID[i]);
if (hWndProducer[i] == NULL)
{
//ErrorHandler(TEXT("CreateThread"));
ExitProcess(3);
}
}
DWORD WINAPI ThrdFunc ( LPVOID n )
{
int *nThreadNo = (int*)n;
char chThreadNo[3];
memset(chThreadNo,0,3);
while(1)
{
itoa(*nThreadNo,chThreadNo,10);
char* pMsg1 = new char[100];
char* pMsg2 = new char[100];
memset(pMsg1,0,100);
memset(pMsg2,0,100);
strcpy(pMsg1," Thread No:");
strcat(pMsg1,chThreadNo);
strcat(pMsg1," Adding Msg:");
PostMessage(stThreadInfoProd.hWndHandle,UWM_ONUPDATEPRODUCERLIST,(WPARAM)pMsg1,0);
}
return 0;
}
Most likely
nThreadNois allocated on the stack. You’re giving each thread a pointer to one of it’s elements.Once the function creating the threads returns, the array is no longer valid, but the thread functions are still pointing to it. The memory the threads are holding pointers to will most likely be overwritten, causing what was originally the thread ID to be overwritten with garbage.
Anything you pass another thread should generally be allocated on heap, either via
malloctype functions ornew, preferablynewsince this is C++.For example, instead of
int nThreadNo[6], useint* nThreadNo = new int[6]. However, keep in mind that you will have todelete[]the memorynThreadNopoints to when you’re done with it.