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 ).
The preponderance of effects of un-thread-safe programming is incorrect results - not program crash.
In many cases you will find the probability of error so low that errors in output is not noticed during development testing, only to find later during production that such an error exists. An un-seasoned developer will assume a position of: "this cannot possibly be a coding error on my part".
Some thread-unsafe coding may never exhibit an error, or will not show an error for years of operation. While thread-safety issues can be exposed by riggorous stress testing and/or by modern tools and practices, you should not become lax and avoid the thurough walk-through of your code with the comprehension of what the other threads (and activity) may be doing at the time of execution of the code under review. Keeping in mind that the code you see in source form is not the code the computer sees at run time.