11

Threadsafe is a term that is thrown around documentation, however there is seldom an explanation of what it means, especially in a language that is understandable to someone learning threading for the first time.

So how do you explain Threadsafe code to someone new to threading? My ideas for options are the moment are:

  • Do you use a list of what makes code thread safe vs. thread unsafe
  • The book definition
  • A useful metaphor
0

8 Answers 8

14

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).

13

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.

3

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,

3

i maybe wrong but one of the criteria for being thread safe is to use local variables only. Using global variables can have undefined result if the same function is called from different threads.

2
  • only partly true since you simply have to protect those global variable with mutexes for instance to have a thread safe function
    – claf
    May 14, 2012 at 17:55
  • @claferri: I think the intent of asking the question was to know what are the things which could lead to unsafe thread. You definitely can use synchronization objects(not just mutex but semaphores/critical sections etc.)to make things thread safe. I wanted to point of one of the things which leads to thread unsafe code. The down-vote was uncalled for.
    – K Singh
    May 15, 2012 at 21:26
2

A thread safe function / object (hereafter referred to as an object) is an object which is designed to support multiple concurrent calls. This can be achieved by serialization of the parallel requests or some sort of support for intertwined calls.

Essentially, if the object safely supports concurrent requests (from multiple threads), it is thread safe. If it is not thread safe, multiple concurrent calls could corrupt its state.

Consider a log book in a hotel. If a person is writing in the book and another person comes along and starts to concurrently write his message, the end result will be a mix of both messages. This can also be demonstrated by several threads writing to an output stream.

0
2

I would say to understand thread safe, start with understanding difference between thread safe function and reentrant function.

Please check The difference between thread-safety and re-entrancy for details.

0

Tread-safe code is code that won't fail because the same data was changed in two places at once. Thread safe is a smaller concept than concurrency-safe, because it presumes that it was in fact two threads of the same program, rather than (say) hardware modifying data, or the OS.

0

A particularly valuable aspect of the term is that it lies on a spectrum of concurrent behavior, where thread safe is the strongest, interrupt safe is a weaker constraint than thread safe, and reentrant even weaker.

In the case of thread safe, this means that the code in question conforms to a consistent api and makes use of resources such that other code in a different thread (such as another, concurrent instance of itself) will not cause an inconsistency, so long as it also conforms to the same use pattern. the use pattern MUST be specified for any reasonable expectation of thread safety to be had.

The interrupt safe constraint doesn't normally appear in modern userland code, because the operating system does a pretty good job of hiding this, however, in kernel mode this is pretty important. This means that the code will complete successfully, even if an interrupt is triggered during its execution.

The last one, reentrant, is almost guaranteed with all modern languages, in and out of userland, and it just means that a section of code may be entered more than once, even if execution has not yet preceeded out of the code section in older cases. This can happen in the case of recursive function calls, for instance. It's very easy to violate the language provided reentrancy by accessing a shared global state variable in the non-reentrant code.

2
  • There are two separate issues involved--the first whether a nested instance of an action must not be started at any point during execution of the first, or whether it may occur at specific permitted points, or at essentially arbitrary points; the second is whether a nested action must complete before the original action can resume. Because multi-tasking is so popular, most routines which can start a nested action will allow it to run concurrent with the first, but it used to be (and in some embedded contexts still is) common for a nested action to save the context of the first...
    – supercat
    Aug 26, 2012 at 15:38
  • 1
    ...when it enters, and restore it on exit. In scenarios that make use of global state, this pattern may be much easier to work with than having multiple live states and the ability to switch between them. It does, however, impose some restrictions on the types of multi-tasking one can do.
    – supercat
    Aug 26, 2012 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.