Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threading Best Practices

Many projects I work on have poor threading implementations and I am the sucker who has to track these down. Is there an accepted best way to handle threading. My code is always waiting for an event that never fires.

I'm kinda thinking like a design pattern or something.

like image 281
patrick Avatar asked Mar 19 '09 00:03

patrick


People also ask

Does threading increase performance?

You can also use threads to improve appeared performance (or responsiveness) in an interactive application. You run heavy computations on a background thread to avoid blocking UI interactions.

What are the principles of multithreading?

Multithreading is a CPU (central processing unit) feature that allows two or more instruction threads to execute independently while sharing the same process resources. A thread is a self-contained sequence of instructions that can execute in parallel with other threads that are part of the same root process.


1 Answers

(Assuming .NET; similar things would apply for other platforms.)

Well, there are lots of things to consider. I'd advise:

  • Immutability is great for multi-threading. Functional programming works well concurrently partly due to the emphasis on immutability.
  • Use locks when you access mutable shared data, both for reads and writes.
  • Don't try to go lock-free unless you really have to. Locks are expensive, but rarely the bottleneck.
  • Monitor.Wait should almost always be part of a condition loop, waiting for a condition to become true and waiting again if it's not.
  • Try to avoid holding locks for longer than you need to.
  • If you ever need to acquire two locks at once, document the ordering thoroughly and make sure you always use the same order.
  • Document the thread-safety of your types. Most types don't need to be thread-safe, they just need to not be thread hostile (i.e. "you can use them from multiple threads, but it's your responsibility to take out locks if you want to share them)
  • Don't access the UI (except in documented thread-safe ways) from a non-UI thread. In Windows Forms, use Control.Invoke/BeginInvoke

That's off the top of my head - I probably think of more if this is useful to you, but I'll stop there in case it's not.

like image 139
Jon Skeet Avatar answered Sep 25 '22 07:09

Jon Skeet