Need help with Multythreads!
Hello, everyone!
I have a problem I don't know how to fix.
I need to create a few threads in a loop sending different arguments in there. Here is a simple version of my code:
for(i = 0; i < lSize; i++)
{
rsPtr = (CEntryTable*)tableArray.GetAt(i);
rs = *rsPtr;
arglist.pRs = pRs;
arglist.pCn = pCn;
arglist.rs = rs;
CreateThread(NULL, 0, BounceProc, (void*)&arglist, 0, NULL);
}
I have 3 entries, so BounceProc is supposed to be called 3 times each time with different arguments. But in reality it receives the last entry all 3 times.I understand it happens because the loop executes too fast, it worked when I put Sleep() after CreateThread(). Is there any other way to solve this problem? I tryed everything I could think of, nothing else worked.
Any ideas?
Thanks,
Irina.
Re: Need help with Multythreads!
You could allocate arglist dynamically and delete it in BounceProc().
Hope this helps.
Regards,
Hoodoo
Re: Need help with Multithreads!
Don't use the same arglist for all calls.
You may use an array of arglists, like this :
CreateThread(NULL, 0, BounceProc, (void*)&arglist [ i ], 0, NULL);
This will ensure your parameters won't be overwritten before they're read.
Re: Need help with Multithreads!
I'm afraid this requires allocating not a single arglist but an array of arglists on a heap - if arglist array is automatic it may go out of scope before the threads process their startup parameters.
Regards,
Hoodoo