There are several ways to ensure thread safety.
It may be reentrant . This means that the function has no state and does not apply to global or static variables, therefore it can be called from several threads at the same time. The term comes from the fact that one thread can enter a function, while another thread is already inside it.
It may have a critical section . This term is often found around, but to be honest, I prefer critical data . A critical section occurs at any time when your code deals with data that is shared across multiple threads. Therefore, I prefer to focus on this important data.
If you use mutex correctly, you can synchronize access to critical data, protecting against insecure stream modifications. Mutexes and locks are very useful, but with great power comes great responsibility. You must not block the same mutex twice in the same thread (which is self-fading). You must be careful if you acquire more than one mutex, as this increases the risk for a dead end. You must consistently protect your data with mutexes.
If all your functions are thread safe and all your shared data is properly protected, your application should be thread safe.
Like crazy Eddie said, this is a huge question. I recommend reading boost streams and using them accordingly.
Low level caveat : compilers can reorder statements, which can lead to loss of thread safety. With multiple cores, each core has its own cache, and you need to properly synchronize caches to ensure thread safety. Also, even if the compiler does not reorder the statements, the hardware can. Thus, a complete guaranteed thread safety is not possible today. You can get 99.99% of how this happens and work with compiler providers and processor manufacturers to eliminate this lingering clause.
Anyway, if you are looking for a checklist to make the class thread safe:
- Define any data common to threads (if you skip it, you cannot protect it)
- create a
boost::mutex m_mutex and use it whenever you try to access shared data (ideally, the shared data is private to the class, so you can be more confident that you are protecting it correctly). - clear globals. Globals are bad anyway, and good luck trying to do something thread safe with global variables.
- Beware of the
static . This is actually not thread safe. Therefore, if you are trying to make a singleton, this will not work correctly. - Beware of the double-check paradigm. Most people who use it are mistaken in some subtle way, and are prone to breakdown due to low levels.
This is an incomplete checklist. I will add more if I think about it, but I hope this is enough to get you started.
Tim Feb 26 '11 at 5:44 2011-02-26 05:44
source share