views:

255

answers:

4

What are the tips you would offer to somebody who is developing a multithreaded application?

The only ones I can think of are:

  • Where it is avoidable, do not have multiple threads writing to the same data structure.

  • Where this cannot be avoided, have critical sections so that the latecoming thread will wait until is complete.

  • Avoid having global variables except constants.

  • Make sure that threads release the resource as soon as they are finished with them.

Can anybody think of anything else?

A: 

Multithreading is a very complex issue - my biggest advice would be to:

  1. Consider if there are any alternatives - often the complexity of multithreading is underestimated.
  2. If you're new to multithreading, start out small and keep things simple - take the time to really understand exactly how your threads are interacting with each other - what threads will be doing the same things at the same time, and what threads will be waiting on each other.

That said, I honestly believe that there is nothing fundamentally difficult about multithreading, it's just that a lot of programmers are so used to single-threaded programming that they make assumptions that aren't valid in multithreaded environments. If you're new to multithreading then you should approach it with extreme care for this reason, however you do get used to it with time.

Kragen
I've got mixed feelings about your item 1... I agree that it's common for people to assume multithreading is the answer when there are performance issues causing the assumption that multithreading is needed--but multithreading is a core concept. Things as small as "I can't click the cancel button!" to "if our server gets x messages it starts ignoring some" are common symptoms caused by a lack of thought put into the necessity of multithreading. It's just another case of needing to know when and when not to
STW
Yeah, I'd agree with that - updated.
Kragen
A: 

Use row-level locking.

Use the TRANSACTION_READ_COMMITTED isolation level.

Avoid queries that cannot use indexes; they require locking of all the rows in the table (if only very briefly) and might block an update.

Multithreading: Programming Tips

joe
A: 

If locking several objects, try to always lock them in the same order. This should minimize your exposure to deadlocks.

Paul Mitchell
+1  A: 

Given the breadth (or ambiguity) of the question, I suggest you pick up a copy of Concurrent Programming on Windows by Joe Duffy, ISBN: 978-0-321-43482-1

STW