Answer the question
In order to leave comments, you need to log in
How to work with callback functions in multi-threaded programs?
Essence of a question:
There is a library. When creating an object of the class of this library, we register a callback and at startup this library creates a thread in which it gets into a blocking read of something, at some event it calls our callback. Callback must be either global or a class member but static (actually, it doesn't matter). What should I do if I need to change the value of the val variable in the callback body, provided that I cannot make this variable static?
#include "LibClass"
int my_callback(int args...) {
// к примеру как здесь адекватно присвоить переменной val значение
}
MyClass {
int val;
LibClass libclass;
public:
MyClass() {
libclass.register_callback(my_callback);
libclass.run();
}
// ... etc
};
Answer the question
In order to leave comments, you need to log in
Usually, a callback is passed this
as a parameter in such cases (most libraries support passing a void*
parameter to callbacks). The variable val
must either be declared public, or getters/setters must be made, or declared my_callback
as friend
for MyClass
. The variable must be protected in the same way as for a normal multi-threaded program. Offhand here may come up std::atomic
or std::mutex
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question