K
K
Kalombyr2021-03-26 11:24:27
Qt
Kalombyr, 2021-03-26 11:24:27

How to make it non-blocking and thread-safe to get a value from a class at any time?

There is an object in a separate thread that quickly creates some value, even if just a counter for now.
Other classes request the value as they are ready.

The question is how to make sure that each "listener" class can receive a value at any time without blocking the generator thread?

That is, the use of Mutexes is eliminated. Through signals, slots are also not an option, because. then the generator will idle emit signals (and copying the value is expensive).

I thought about writing first to one variable, then to another, but then it can still be written to the one that is now being read by someone ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2021-03-26
@Kalombyr

https://doc.qt.io/qt-5/atomic-operations.html

I
Ighor July, 2021-03-26
@IGHOR

Directly can be safely accessed only if the method does not have a record in the memory of the class itself.
If there is just a counter, then you should use a mutex.
It is possible to organize a request-response mechanism using the Qt slots signal mechanism.
It is also possible to connect a signal slot with the Qt::BlockingQueuedConnection type, but this will work in the same way as with a mutex.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question