Generally thread-safe means your code will not break due to unexpected changes to variables that are shared between threads but where the code was never written with consideration that multiple threads may concurrently be executing the code.
A good and simple example of this would be code that manages a linked list. The extraction might look like:
node = head;
if(node) head = node.next;
This looks safe enough but what if thread A picks up the head node, then before updating the head pointer thread B inserts a new head node, then thread A updates the head node with node.next. Under this circumstance the node inserted by B would be lost.
This two line code example is not thread safe. The window of error opportunity is quite small in this code exampleand may not be noticed for a long time. And may not be noticed during debugging. It might only occure once the code passes verification test and gets into the field.
Consider a financial software that does one transaction in a multi-threaded environment ( many users are
using software at the same time ):
Transfer $1 from AccountA to AccountB.
It will be athread-safetransaction onlyin one case if the transaction is not interrupted until it is completed.
A pseudo-code could look like:
ISOLATION LEVEL: Set to Exclusive
COMMIT if everything is OK, or ROLLBACK in case of an error
ISOLATION LEVEL: Set to Shared
That scheme guarantees that the balance of a financial organizationis correct at the end of thetransaction. In
overall, some set of synchronization objects has to be used, like mutexes, critical sections, events, or
semaphors, to isolate some piece of codeor adatabase datafrom simultaneous modifications from different threads ( users ).