
| Subject: | Can I reuse a thread in a loop? |
| Posted by: | Pete Sergeant |
| Date: | Sun, 31 Aug 2008 |
Hi,
In a nutshell, can I reuse a thread once it has finished, and if so, how do I get it to run again?
I have a thread class that does some number crunching (mainly matrix multiplications) on global arrays. Each thread gets start and stop indices of what to crunch. The algorithm below works fine, correct answers, good performance increase.
repeat
{ Create and define threads }
for i := 0 to 3 do
begin
create_threads(suspended)
set_thread_parameters, including FreeOnTerminate := True
end
{ Set threads going }
for i := 0 to 3
set_threads_running (via Resume)
{ Wait for them all to finish }
WaitForMultipleObjects(required bits)
{ Check global variables to determine if more calculations are required }
Converged := convergence_check
until converged
However, my initial attempt was to create the threads once before the convergence loop and to not free them, i.e. FreeOnTerminate := False. This I would do after the loop. It seemed to be the faster way, as there must be some overhead to creating the threads each loop (there are 200 to 5000 iterations per loop, depending on the problem). I simply cannot get it to work. I've tried calling Resume on the first pass, Execute on subsequent passes, but that didn't help.
Any ideas on what I've missed, or is it actually better to create the thread each pass, i.e. let the system allocate the 'best' core for the job at that moment in time? Delphi 7 by the way, still the best :)
Thanks
Pete
Edited by: Pete Sergeant on Aug 31, 2008 1:42 AM