Hariprasad
Hariprasad

Reputation: 3642

QObject reentrancy and thread safety

In this article, it is said that : Some of QObjects are reentrant, making it possible to use these classes from multiple threads simultaneously.

I suppose that a piece of code which is reentrant is also supposed to be thread-safe.

But, the same article continues to say that:

Note that these classes are designed to be created and used from within a single thread; creating an object in one thread and calling its functions from another thread is not guaranteed to work.

Isn't this contradictory? What does it finally mean? Can I safely call QObject functions across threads?

I have copied the relevant portion of the article below:

QObject Reentrancy

QObject is reentrant. Most of its non-GUI subclasses, such as QTimer, QTcpSocket, QUdpSocket, QFtp, and QProcess, are also reentrant, making it possible to use these classes from multiple threads simultaneously. Note that these classes are designed to be created and used from within a single thread; creating an object in one thread and calling its functions from another thread is not guaranteed to work.

Upvotes: 4

Views: 546

Answers (1)

László Papp
László Papp

Reputation: 53155

I think the following quote from the documentation below should help you to understand the difference between them. In short, please note that the first quote you are referring is writing about the class itself, and the second the object which is an instance of a class.

Reentrancy and Thread-Safety

Throughout the documentation, the terms reentrant and thread-safe are used to mark classes and functions to indicate how they can be used in multithread applications:

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

By extension, 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.

Note: Qt classes are only documented as thread-safe if they are intended to be used by multiple threads. If a function is not marked as thread-safe or reentrant, it should not be used from different threads. If a class is not marked as thread-safe or reentrant then a specific instance of that class should not be accessed from different threads.

Upvotes: 4

Related Questions