V
V
Vitaly Stolyarov2016-12-11 15:15:02
C++ / C#
Vitaly Stolyarov, 2016-12-11 15:15:02

Lambda Callback from Pthread?

The task is to pass a function to the lambda thread to handle, for example, the thread completion event (onload, or maybe onprogress).
I do it like this:

struct Arg {
    void (*func)();
};


void* threadFunction(void *arg) {

      ((Arg*) arg)->func();
}

void Network::open(const char * url, void (*onload)()) {

Arg* arg;
 arg->func = onload; /// сюда передается какая-то лямбда из внешнего метода []() {   };  
    pthread_attr_init(&attr);

    rc = pthread_create(&thread[0], &attr, threadFunction, arg);
    if (rc) {
        Logger::log("ERROR; return code from pthread_create() is %d\n", rc);
        return;
    }

    pthread_attr_destroy(&attr);
}

And without waiting for the thread to complete, I get RUN FINISHED; segmentation fault; core-dumped; , and this happens once in a while.
It turns out that onload is deleted without waiting for the execution of the thread, although it is just necessary that it be saved. How to solve it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2016-12-15
@Ni55aN

1) worth initializing Arg: Arg* arg = new Arg;
Don't forget to remove it at the end of use (as I understand it in threadFunction).
2) Use std::function<void()>functions instead of c-style to avoid unnecessary lambda removal problems.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question