I am writing in C ++ Builder. There is a dynamic list of objects. For each object, an estimate is calculated. Now such a calculation for all objects in the list is implemented in a cycle. Since the estimation calculation algorithm uses only the data of a specific object, it makes sense to execute it simultaneously for several objects simultaneously in parallel streams. What I actually tried to do:
cEstimationThread * pFirstThread=new cEstimationThread(true); cEstimationThread * pSecondThread=new cEstimationThread(true); for(cChromosome * curChromosome=startChromosome;curChromosome;) { if(!pFirstThread->bRunning) { pFirstThread->SetValuesForEstimation( curChromosome, arrUnitSets, arrUncertSets, iNumOfVars, iNumOfSets, iNumOfUnitSets, iCoverWeight); pFirstThread->Resume(); curChromosome=curChromosome->next; } if(curChromosome) { if(!pSecondThread->bRunning) { pSecondThread->SetValuesForEstimation( curChromosome, arrUnitSets, arrUncertSets, iNumOfVars, iNumOfSets, iNumOfUnitSets, iCoverWeight); pSecondThread->Resume(); curChromosome=curChromosome->next; } } while(pFirstThread->bRunning&&pSecondThread->bRunning); } while(pFirstThread->bRunning||pSecondThread->bRunning); pFirstThread->FreeOnTerminate=true; pSecondThread->FreeOnTerminate=true; pFirstThread->Terminate(); pSecondThread->Terminate();
Here, two threads are created, pFirstThread
and pSecondThread
, then the first stream contains a link to the next curChromosome
object, pointers to the dynamic arrays arrUnitSets
, arrUncertSets
(used only for reading) and a few more variables for calculation (recorded by value, used only for reading). Then the first thread is launched for execution. Then, the next object is entered into the second stream, and so on.
After that, in the while(pFirstThread->bRunning&&pSecondThread->bRunning)
line while(pFirstThread->bRunning&&pSecondThread->bRunning)
, I think I implemented waiting for both threads to execute (the bRunning
variable at the beginning of the thread's code is true
, and after it is false
). As soon as the list of objects ends, the threads are destroyed.
The code, oddly enough :), turned out to be inoperative. When step-by-step debugging happens, something strange happens: the code of the main thread is executed, then pFirstThread
, but it is not clear how this is determined.
In this regard, two questions:
- How in the case of two OS processors (WinXP) determines which thread to start and which one to suspend (they will not run at the same time anyway)?
- Is it possible to synchronize the execution of threads in this way:
while(pFirstThread->bRunning&&pSecondThread->bRunning)
?