V
V
Vi Vola2018-11-01 16:11:09
C++ / C#
Vi Vola, 2018-11-01 16:11:09

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 
};

UPD:
I forgot to clarify that I can’t get into LibClass and change the implementation, so I can’t change the callback either, its arguments will always be the same

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Gerasimov, 2018-11-01
@hakain

Usually, a callback is passed thisas a parameter in such cases (most libraries support passing a void*parameter to callbacks). The variable valmust either be declared public, or getters/setters must be made, or declared my_callbackas friendfor MyClass. The variable must be protected in the same way as for a normal multi-threaded program. Offhand here may come up std::atomicor std::mutex.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question