开发者

Difference between Re-entrant and Thread-Safe function

开发者 https://www.devze.com 2022-12-20 04:48 出处:网络
What is the difference between a re-entrant function and a thread saf开发者_如何学运维e function?

What is the difference between a re-entrant function and a thread saf开发者_如何学运维e function?


  • 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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消