Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep threads idle or kill them / restart them?

Pseudo-situation: have a class (let's say BackgroundMagic), and it has Start() and Stop() methods. The work in this class is done by one single thread, and is simply a short loop every X milliseconds.

Which of these options is better, as far as managing the stopping/starting? Can't decide which road to take.

  1. The first time Start() is called, initialize and start the thread with IsBackground = true. Use a simple bool flag to indicate on each loop around whether it should actually do any work, or just sleep. After initial initialization, let Stop() and Start() simply control the bool flag. The thread will just be stopped and cleaned up by the runtime since IsBackground = true when the app exits.
  2. Forcefully abort/join/interrupt/whatever on Stop, and recreate the thread again on Start(), not leaving the thread lying around.

... or any better/cleaner ways of doing this?

like image 472
Brandon Avatar asked Nov 07 '09 22:11

Brandon


2 Answers

Neither! Use a Thread Pool!

like image 62
Dave Markle Avatar answered Oct 30 '22 15:10

Dave Markle


Thread creation is fairly expensive, so the standard "industrial-strength" way to do this is to control the thread with a flag. For a larger-scale variant on the same idea, consider the thread pools that e.g. Apache uses to manage thousands of threads without a lot of explicit state or a painful performance hit.

So in the abstract, I'd vote for your option #1. But if performance isn't a concern and the option #2 code is easier to reason about, go for it.

like image 41
David Seiler Avatar answered Oct 30 '22 15:10

David Seiler