9

What is the difference between a re-entrant function and a thread safe function?

Jay
  • 24,173
  • 25
  • 93
  • 141

3 Answers3

2

Re-entrant means no global state (local only).

Thread safe means it is not possible for 2 (or more) threads to conflict with each other (by writing conflicting values).

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
2
  • A thread-safe function can be called simultaneously from multiple threads, even when the invocations use shared data, because all references to the shared data are serialized.

  • A reentrant function can also be called simultaneously from multiple threads, but only if each invocation uses its own data.

Hence, a thread-safe function is always reentrant, but a reentrant function is not always thread-safe.

The difference can be cottoned on with the example,

A class is said to be reentrant if its member functions can be called safely from multiple threads, as long as each thread uses a different instance of the class. The class is thread-safe if its member functions can be called safely from multiple threads, even if all the threads use the same instance of the class.

Source: Qt

Community
  • 1
  • 1
1

Did you check the wiki article on the subject. It explains it well so please see that for a full discussion.

A few relevant bits from the article:

In computing, a computer program or subroutine is called reentrant if it can be interrupted in the middle of its execution, and then be safely called again ("re-entered") before its previous invocations complete execution. The interruption could be caused by an internal action such as a jump or call, or by an external action such as a hardware interrupt or signal. Once the reentered invocation completes, the previous invocations will resume correct execution.

and

This definition of reentrancy differs from that of thread-safety in multi-threaded environments. A reentrant subroutine can achieve thread-safety, but being reentrant alone might not be sufficient to be thread-safe in all situations. Conversely, thread-safe code does not necessarily have to be reentrant (see below for examples).

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
  • 4
    Please post an actual answer that summarizes the link in case it goes cold (as is the case here and now). – nedR Mar 26 '15 at 06:13