Home > Mobile >  Lambda expressions in thread pool in C
Lambda expressions in thread pool in C

Time:12-12

I am trying to push a bunch of lambda expressions on a thread pool in C . I know there are no in-built thread pool implementations in C (or at least that is what I read so far), so I used the one I found at: https://github.com/vit-vit/ctpl (I found it through this stackoverflow answer). I managed to use it when I had lambda expressions which would return basic C types (int, double, etc), but I cannot get it to work when I have a lambda expression which returns a custom class instance. I made a simple example to illustrate my problem, using this dummy class Person.

This is the dummy class Person:

class Person {
private:
    std::string name;
    int age;

public:
    Person(std::string name, int age) : name(std::move(name)), age(age) {}

    std::string getName() const { return name; }

    int getAge() const { return age; }
};

And I have this function in my main file which just creates an instance of the Person class:

Person generatePersonInstance(std::string name, int age) {
    return Person(std::move(name), age);
}

And then I just try to use the thread pool (again, the one I found at https://github.com/vit-vit/ctpl) with a lambda expression which returns a Person instance:

#include "ctpl_stl.h"
#include "Person.h"

int main() {
    std::string myName = "myName";
    int myAge = 100;

    ctpl::thread_pool pool(4);
    std::future<Person> f = pool.push([&myName, &myAge]{ generatePersonInstance(myName, myAge); });

    return 0;
}

As you can see, I am trying to push on the thread pool a lambda expression which will just return a Person instance with the given parameters. The idea is that after this code runs, I can run f.get() to get the Person instance itself from the std::future<Person> instance. But my problem is that this code does not run, and I don't know why. At the pool.push part I get the error:

No matching member function for call to 'push' candidate template ignored: substitution failure [with F = (lambda at D:<my_path>\main.cpp:146:39), Rest = <>]: no matching function for call to object of type '(lambda at D:<my_path>\main... candidate template ignored: substitution failure [with F = (lambda at D:<my_path>\main.cpp:146:39)]: no matching function for call to object of type '(lambda at D:<my_path>\main.cpp:146:39)'

How can I fix this and make the code work as I intended?

CodePudding user response:

I see 2 issues:

  1. You're missing a return of Person in the lambda.

  2. It looks like the argument of ctpl::push must accept an int thread ID.

std::future<Person> f = pool.push([&myName, &myAge](int id) {
    return generatePersonInstance(myName, myAge);
});
  • Related