2

I have a function which looks like below

I want to call lambda expression from pthread created threads.

void parallel(int start, int end, std::function<void(int)&&lambda, int noThreads>){
....
....
pthread_create(&threadid, NULL, startRoutine, args);//Want to call lambda(1) from the created thread
lambda(2);//Works fine from the main thread
....
....
}

How should I pass my lambda function to the startRoutine of the thread? and call lambda(1) from the startRoutine?.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
srccode
  • 721
  • 4
  • 16

1 Answers1

2

You can not cast std::function to function pointer. But you can use std::thread, which will work with any callbable, including std::function.

If, for whatever reason, you can't use std::thread, you can create a local class and a static member function there, to call the std::function.

Something along following lines:

#include <functional>
#include <pthread.h>

void parallel(std::function<void(int)>&& lambda){
    struct caller {
        static void* callme_static(void* me) {
            return static_cast<caller*>(me)->callme();
        }
        void* callme() {
            callable(arg);
            return nullptr;
        }
        caller(std::function<void(int)> c, int a) : callable(c),
                                                      arg(a)   {}

        std::function<void(int)> callable;
        const int arg;
    };
    pthread_t threadid;

    int arg = 0;
    caller c(lambda, arg);

    //Want to call lambda(1) from the created thread
    pthread_create(&threadid, NULL, &caller::callme_static, &c);
}

This could be generalized into universal caller, but that would be exactly what std::thread already does, so if universal caller is desired, one could simply copy-paste std::thread.

SergeyA
  • 61,605
  • 5
  • 78
  • 137