Jump to content

  • Log In with Google      Sign In   
  • Create Account

How to restart thread?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 Ripiz   Members   -  Reputation: 529

Like
0Likes
Like

Posted 11 January 2012 - 06:39 PM

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.

Sponsor:

#2 Telastyn   Crossbones+   -  Reputation: 3730

Like
0Likes
Like

Posted 11 January 2012 - 06:43 PM

Thread pools are the common way to solve this problem.

#3 e‍dd   Members   -  Reputation: 2105

Like
2Likes
Like

Posted 11 January 2012 - 07:04 PM

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.

#4 medv4380   Members   -  Reputation: 98

Like
0Likes
Like

Posted 12 January 2012 - 02:07 PM

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.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS