How to define threadsafe?

Multithreading leads to non-deterministic execution - You don't know exactly when a certain piece of parallel code is run.

Given that, this wonderful multithreading tutorial defines thread safety like this:

Thread-safe code is code which has no indeterminacy in the face of any multithreading scenario. Thread-safety is achieved primarily with locking, and by reducing the possibilities for interaction between threads.

This means no matter how the threads are run in particular, the behaviour is always well-defined (and therefore free from race conditions).


Eric Lippert says:

When I'm asked "is this code thread safe?" I always have to push back and ask "what are the exact threading scenarios you are concerned about?" and "exactly what is correct behaviour of the object in every one of those scenarios?".

It is unhelpful to say that code is "thread safe" without somehow communicating what undesirable behaviors the utilized thread safety mechanisms do and do not prevent.


G'day,

A good place to start is to have a read of the POSIX paper on thread safety.

Edit: Just the first few paragraphs give you a quick overview of thread safety and re-entrant code.

HTH

cheers,