Keep threads idle or kill them / restart them?

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.


BackgroundMagic


Start()


Stop()



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


IsBackground


IsBackground



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




6 Answers
6



Neither! Use a Thread Pool!



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.



A mutex or semaphore would be a better option than a simple boolean flag, because it doesn't require checking the state of the flag repeatedly. Simply block on the mutex/semaphore, and when you want the thread to run, release the mutex/semaphore and the thread will run once.



The thread pool is not appropriate for long-running tasks. The thread pool is ideal for short tasks where the overhead of thread creation increases the overhead of the operation by a large percentage. This is also true of the TPL (Task Parallel Library) in the .NET 4 framework.



Using a thread dedicated to do this work is probably a good idea, but how you manage it can be a big deal. If you simply do a Thread.Sleep between checking for work then that is less effective because now you have the thread spinning for no good reason. This is called a spin lock (kind of) and is only effective if you know the resource you are waiting for is going to release the lock very soon. It would be a far better idea to use an AutoResetEvent. This way the thread only wakes up because the producer thread signaled that there is work to do. This has the advantage of not wasting CPU resources to schedule the thread if there is nothing to do and it allows for less delay between the producer and consumer.


Thread.Sleep


AutoResetEvent



To answer your question directly, yes you can use some kind of bool to gracefully shutdown the thread (I would mark it as volatile though). This is much better than aborting the thread!


bool


volatile



See:



You can also use a bool flag to indicate if the thread should stop. Which gives you your interrupt and stop code. So two bools one for if there is work and one to stop the loop.



The other thing you could consider is using the Dispose pattern and cleaning up the thread when the object is disposed.



I would use the bool flag, but you need to be sure it is either correctly locked or only set from one thread. Your loop should look like this


while (true)

if (shouldSleep)

Thread.Sleep(interval);
continue;


doSomeWork();

if (shouldCancel)

CleanUpResources();
break;




This makes sure you can send the thread to sleep but also correctly terminate it. Killing a thread is never a good idea if you can avoid it as the thread doesn't have a chance to clean up any resources used. You need to decide on an appropriate sleep interval though. It will determine the latency your thread needs to start up.



The second option is rather expensive, thread creation involves some OS resources and startup time is also considerable. If thread recreation won't happen often and the amount of work performed is large enough this would be reasonable. You can avoid the complexity involved in the loop approach.



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ