What is it? I was reading Effective STL and came across it. I have also Googled it, but couldn't get any helpful info.

closed as too broad by gnat, user40980, Dan Pichelman, GlenH7, Bart van Ingen Schenau Dec 21 '14 at 16:24

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    Anything specific you wouldn't understand in the Wikipedia article about Thread safety – thorsten müller Dec 14 '12 at 14:59
  • 1
    Joseph Albahari has the best tutorial on thread safety and concurrency that I've seen. albahari.com/threading – Robert Harvey Dec 14 '12 at 16:39
  • @thorstenmüller The Wikipedia definition is somewhat cyclical: "a piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time" => a code is thread safe if it guarantees safe execution by multiple threads... – assylias Dec 14 '12 at 17:28
  • 1
    @assylias: yes, that's the first sentence (btw more or less like your quote: "A [portion of code] is thread-safe if it behaves correctly when accessed from multiple threads") and then it goes on describing everything in tiny detail and linking to other articles describing even more details. Just wondering why OP claims notto be able to get any helpful info from Google about such a common concept. – thorsten müller Dec 14 '12 at 19:02
  • What is this thing you call thread safe? by Eric Lippert – Robert Harvey Dec 14 '12 at 22:28

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:

A [portion of code] is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.

By correctly they mean that the program behaves in compliance with its specifications.

Contrived example

Imagine that you implement a counter. You could say that it behaves correctly if:

  • counter.next() never returns a value that has already been returned before (we assume no overflow etc. for simplicity)
  • all values from 0 to the current value have been returned at some stage (no value is skipped)

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 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:

void an_object::member_function()
    if (p != nullptr)   // 1
        delete p;       // 2
        p = new int(10);// 3
    int q = *p;         // 4

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:

scenario 1:

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)

scenario 2:

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.

  • That's a good part your own silly fault. That code is also exception-unsafe and a whole bunch of other unsafe. – DeadMG Dec 14 '12 at 20:16
  • @DeadMG - the code I posted as an example is purposefully unsafe. I didn't write it as a good example of code but as a good example of "unsafe crashy" code. I also do not understand what you mean. My own silly fault for what? – utnapistim Dec 17 '12 at 9:55

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

  • This is not a good example. The database backing the ORM already has ways of dealing with this kind of data contention. – Robert Harvey Dec 14 '12 at 16:06
  • That is a foolish leap in logic. That is true, a database can deal with data contention but the database does not manage the ORM's internal state. You could just open up a debugger (if you have the ORM's source), stop both threads before the persistence routine and run them both without any sanity checks. I think it's a great example. I'm not even talking about atomized transactions, which obviously the database is capable of. – brian Dec 14 '12 at 16:17
  • Well, presumably the ORM is not a POS, and it does what it's supposed to do. A better example would be locking the internal data member of a class when writing to it in order to make a method or property re-entrant; thread-safety is not normally associated with writing to databases (or their ORM brethren) because, as I said before, they already have mechanisms for dealing with write contention. – Robert Harvey Dec 14 '12 at 16:21
  • You are overthinking it :) I'm talking about all the sanity checks and state management that has to happen before SQL would even get sent to the database, and then the decision to tag entities as persisted. ORMs encapsulate a ton of state and that's why there are thread safety concerns with all of them, if you don't think so, you're plain wrong! – brian Dec 14 '12 at 16:23
  • 1
    All I'm saying is you're discussing a fairly advanced topic involving a number of different software layers, but the OP is asking a fairly basic question. You're the one complicating the topic, not me. The sarcasm is unnecessary; we're both professionals, aren't we? – Robert Harvey Dec 14 '12 at 17:05

Something is thread safe if it can be used from several threads without malfunctioning.

  • 1
    That seems self-evident – Robert Harvey Dec 14 '12 at 18:18
  • 1
    Short, simple question calls for ditto answer. – Minthos Dec 14 '12 at 18:32

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