Achieving Thread-Safety

Posted by Smasher on Stack Overflow See other posts from Stack Overflow or by Smasher
Published on 2009-02-19T07:46:23Z Indexed on 2010/06/07 14:32 UTC
Read the original article Hit count: 275

Question How can I make sure my application is thread-safe? Are their any common practices, testing methods, things to avoid, things to look for?

Background I'm currently developing a server application that performs a number of background tasks in different threads and communicates with clients using Indy (using another bunch of automatically generated threads for the communication). Since the application should be highly availabe, a program crash is a very bad thing and I want to make sure that the application is thread-safe. No matter what, from time to time I discover a piece of code that throws an exception that never occured before and in most cases I realize that it is some kind of synchronization bug, where I forgot to synchronize my objects properly. Hence my question concerning best practices, testing of thread-safety and things like that.

mghie: Thanks for the answer! I should perhaps be a little bit more precise. Just to be clear, I know about the principles of multithreading, I use synchronization (monitors) throughout my program and I know how to differentiate threading problems from other implementation problems. But nevertheless, I keep forgetting to add proper synchronization from time to time. Just to give an example, I used the RTL sort function in my code. Looked something like

FKeyList.Sort (CompareKeysFunc);

Turns out, that I had to synchronize FKeyList while sorting. It just don't came to my mind when initially writing that simple line of code. It's these thins I wanna talk about. What are the places where one easily forgets to add synchronization code? How do YOU make sure that you added sync code in all important places?

© Stack Overflow or respective owner

Related posts about best-practices

Related posts about multithreading