views:

177

answers:

4

Possible Duplicate:
What are common concurrency pitfalls?

I have basic knowledge of threading, nothing specific. Some co-workers and I are studying for a certification and we are on the chapter about multi-threading.

What are some common mistakes you make when implementing a multi-threaded application?

When developing a multi-threaded app, are there any "gotchas" we should look out for?

+1  A: 

The classic difficulty with multithreaded applications is two different threads modifying the same memory at the same time. The method of solving this problem is called synchronization.

See my more complete answer here.

Robert Harvey
+1  A: 

Check out Joe Albahari's Free E-Book on Threading

Mitch Wheat
A: 

the biggest gotchas are

  • updating data from different threads (concurrent writes); even something as simple as i++ is not always atomic, or in other words if two threads do it at the same time the result might be i+=2 or it might be i++ (or it might be anything at all depending what the language you're using); the answer is to make sure write access is "synchronized" on a "mutex" (mutual exclusion) lock so that at most one thread can write to that volatile block of data at a given time

  • deadlocks, where one thread has to acquire a mutex on A then a mutex on B, and another thread acquires the mutexes in the reverse order; if the first thread gets A, and the second thread gets B, then neither thread can proceed; the answer here is to make sure mutexes are acquired in a canonical order

but the best advice is to KISS, keep it simple stupid. complex threading models are incredibly painful to debug. don't have multiple threads making writes, if at all possible, and especially try to avoid multiple nested mutex locks (needing both A and B to do something).

another piece of advice is to use well-known libraries of thread-safe data types such as atomic objects and concurrent maps and queues.

considering the future (cloud computing) you might consider writing your application as if the threads are on different machines, cross-communicating as little as possible.

Partly Cloudy
A: 

I think the biggest gotcha is forgetting if multiple areas can be starting threads, as you may have race conditions, as one section may be synchronized but if there is another entry point you will have a hard problem to track down.

But, the hardest part is knowing when to use multi-threading. It isn't perfect for every situation.

What parameters should be passed in, and how few global variables can you get away with.

I think there is a great deal of good ideas coming from functional programming, to limit side effects, as you start to learn that largely global variables can be bad, if they are changeable by many different threads.

Debugging when you have multiple threads will also be a challenge, depending on the language you use, for example, using a C debugger on unix is not fun, but Visual Studio makes it easier.

James Black