简体   繁体   English

如何将 C++ 中的 pthreads 库与函数式 lambda 一起使用?

[英]How to use the pthreads library in C++ with functional lambdas?

I want to use the pthreads library in C++ with C++ lambdas.我想将 C++ 中的 pthreads 库与 C++ lambda 一起使用。 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.我的 lambda 是std::function<void(X)>类型,其中 X 可以是任何类型,例如intdoublefloat或自定义类型。 Moreover, it is possible that the lambda accepts more than one parameter.此外,lambda 可能接受多个参数。 For example, I can have a lambda of the type std::function<void(float,int)> .例如,我可以有一个类型为std::function<void(float,int)>的 lambda。 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.现在我想将此 lambda 转换为 C 样式的 function 指针,该指针采用单个void* arguments 并返回void*类型。 So I want to cast my lambda to a function pointer of the type void* (*)(void*) .所以我想将我的 lambda 转换为类型为void* (*)(void*)的 function 指针。

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?我想这样做,以便我可以将此 function 指针传递给 pthread_create API。有人可以告诉我该怎么做吗?

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.我认为由于目标类型接受一个void*参数,我需要创建一个类型为void* my_wrapper(void*)的包装器 function,它将在其主体内调用 lambda。 Then I think I should be able to pass a pointer to the wrapper to the pthreads API.然后我想我应该能够将指向包装器的指针传递给 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.此外,我还需要一种方法来捕获 lambda arguments 以便我可以将它们包装在一个自定义结构中,然后我可以将其指针传递给包装器。

Start by creating a lambda, callable without parameters and returning void * .首先创建一个 lambda,可在没有参数的情况下调用并返回void * Presumably it'd call your std::function with an appropriate parameter.大概它会用适当的参数调用你的std::function

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

Then create another lambda:然后创建另一个 lambda:

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

caller(&lambda) calls lambda() . caller(&lambda)调用lambda()

Now you can pass caller to pthread_create , with &lambda as the argument.现在您可以将caller传递给pthread_create ,并将&lambda作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM