Sign in to follow this  
Ripiz

How to restart thread?

Recommended Posts

Ripiz    539
How can I restart thread after it finished executing?
Consider following pseudocode:
[CODE]
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;
};
[/CODE]

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.

Share this post


Link to post
Share on other sites
the_edd    2109
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.

Share this post


Link to post
Share on other sites
medv4380    98
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.
[url="http://blog.think-async.com/2008/10/asynchronous-forkjoin-using-asio.html"]http://blog.think-async.com/2008/10/asynchronous-forkjoin-using-asio.html[/url]
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this