How to restart thread?

Started by
2 comments, last by medv4380 12 years, 3 months ago
How can I restart thread after it finished executing?
Consider following pseudocode:

HANDLE Thread1 = CreateThread(Function1);
HANDLE Thread2 = CreateThread(Function2);
while(Program_Running) {
RunThread(Thread1);
RunThread(Thread2);
Function3();
WaitToFinish(Thread1);
WaitToFinish(Thread2);
Data = Function1_Result + Function1_Result + Function2_Result + Function3_Result;
};


To speedup process I decide to use multithreading, so I create 2 extra threads to do calculations, but they should be executed only when I need it, therefore it cannot be infinite loop. However creating new thread every iteration is quite slow. That's why I'm looking for a way how to restart thread. If that is not possible, what would be best way to execute threads only when I need them to, without having that overhead of recreating threads?

Thank you in advance.
Advertisement
Thread pools are the common way to solve this problem.
The threads should be there for the duration of the application, but accept work via queues. While the threads are waiting for work, they won't be eating CPU time. To implement this, you'd use condition variables, semaphores, or Windows events. This is essentially what a thread pool does, as Telastyn suggested.
You actually need to use a JoinFork model for what you're using. It'll also need a JoinFork Thread pool to minimize the creation of many threads.
http://blog.think-async.com/2008/10/asynchronous-forkjoin-using-asio.html
If you use a regular Thread Pool you'll need to find a Phaser that you can use to keep them in Sync.

A word of warning. If those threads you want to use are small fine grained tasks then be sure to build a test case to check and make sure you actually made good code. Fine Grained parallelism usually slows the system down making the serial version of the code superior because of the Sync costs.

If you can redesign to use Message Passing that would be best but can be harder to understand and design around.

This topic is closed to new replies.

Advertisement