Home > front end >  How to use the pthreads library in C with functional lambdas?
How to use the pthreads library in C with functional lambdas?

Time:01-27

I want to use the pthreads library in C with C lambdas. My lambdas are of the type std::function<void(X)> when X can be any type such as int, double, float or a custom type. Moreover, it is possible that the lambda accepts more than one parameter. For example, I can have a lambda of the type std::function<void(float,int)>. Now I want to cast this lambda to a C style function pointer which takes in a single void* arguments and returns a void* type. So I want to cast my lambda to a function pointer of the type void* (*)(void*).

I want to do this so that I can pass this function pointer to the pthread_create API. Can someone please tell me how can I do this?

I think that since the target type accepts a void* argument, I'll need to create a wrapper function of the type void* my_wrapper(void*) which would call the lambda inside its body. Then I think I should be able to pass a pointer to the wrapper to the pthreads API.

Moreover, I will also need a way to capture the lambda arguments so that I can wrap them up in a custom structure whose pointer I can then pass to the wrapper.

CodePudding user response:

Start by creating a lambda, callable without parameters and returning void *. Presumably it'd call your std::function with an appropriate parameter.

auto lambda = [&]() -> void *
{
    std::cout << "Hello, world!\n";
    return nullptr;
};

Then create another lambda:

auto caller = [](void *data) -> void *
{
    return (*static_cast<decltype(lambda) *>(data))();
};

caller(&lambda) calls lambda().

Now you can pass caller to pthread_create, with &lambda as the argument.

  • Related