What is it? I was reading Effective STL and came across it. I have also Googled it, but couldn't get any helpful info.
Something is thread safe if it can be used from several threads without malfunctioning.
In essence, many things can go wrong in a multi threaded environment (instructions reordering, partially constructed objects, same variable having different values in different threads because of caching at the CPU level etc.).
I like the definition given by Java Concurrency in Practice:
By correctly they mean that the program behaves in compliance with its specifications.
Imagine that you implement a counter. You could say that it behaves correctly if:
A thread safe counter would behave according to those rules regardless of how many threads access it concurrently (which would typically not be the case of a naive implementation).
Thread safety was best solidified in my mind when I thought about it in terms of an ORM.
When your ORM goes to save all your objects to the database, it's not thread safe.
Why? Well, part of an ORM's responsibility is to track a lot of internal state (In order to figure out what to do when it comes time to actually do persistence). If you are half way through all the state management routines for a call to 'Save' and you start running a secondary 'Save' routine, what the heck is going to happen? You will be disappointed with the results if you were hoping for good things to happen.
This is such a good example because thread safety is all about whether or not the state of objects can "survive" a second entry to a routine.
(Also why anyone who creates a static repository for their web app is shamed relentlessly.)
|show 4 more comments|
Thread safety is a generic term that relates to avoiding R/W and synchronization problems, in the presence of multiple threads accessing the same data.
In practice, when two (or more) threads access the same data and at least one modifies the data, the other thread may be either reach an inconsistent state, or read corrupted data (the code is not "thread-safe").
To avoid this, there is a whole set of techniques in C++ (various mutex implementations, events, "double lock checking pattern", std::atomic and a lot more).
For a simple example, consider:
Consider two threads executing an_object::member_function for the same object instance, where p and q belong to an_object.
Here are some scenarios:
thread 1 executes line 1
thread 2 executes line 1
thread 1 executes line 2
thread 2 executes line 2 and you have a double delete (and undefined behavior ensues)
thread 1 executes line 1, 2 and 3
thread 2 executes line 1 and 2
thread 1 executes line 4, using an address just deleted by thread 2 (and undefined behavior appears again).
There are many more scenarios leading to undefined behavior with these four lines of code.