progschj / ThreadPool

A simple C++11 Thread Pool implementation
zlib License
7.64k stars 2.21k forks source link

threadpool for member function #48

Closed RemoteSensingFrank closed 6 years ago

RemoteSensingFrank commented 6 years ago

hi I wonder how can i use the threadpool for member funtion in class and my code like:

UAVProcessThreadPool threadPool(2); std::vector<std::future> errReturn; for(const auto iter:feature) { errReturn.emplace_back(threadPool.UAVProcess_Enterqueue( [](FeatureParam param){UAVProcessFeatExtractEach(param);} ,&iter.second )); }

the code is in member funtion and function UAVProcessFeatExtractEach is also a member funtion, could you please show me a sample of how to use the threadpool in condition like this?

Quartzeee commented 6 years ago

Not sure but wouldn't it be the same syntax as any other member function call?

UAVProcessThreadPool threadPool(2);
std::vector<std::future> errReturn;

for(const auto iter:feature)
{
    errReturn.emplace_back(threadPool.UAVProcess_Enterqueue( [](FeatureParam param){ bind(&UAVProcessThreadPool::UAVProcessFeatExtractEach, this, param); },&iter.second));
}
RemoteSensingFrank commented 6 years ago

Thanks for your reply and I tried a very simple demo like ` class test { public: void TmpText() { ThreadPool tp(8); std::vector< std::future > results; int num = 3; for (int i = 0; i < 8; ++i) { results.emplace_back(tp.enqueue([i](int param) {std::bind(&test::num, param);},&num)); }

    //tp.enqueue([](int param) { std::bind(&test::num, this, param); }, &num);
}

int num(int i)
{
    return i*i;
}

};` the error is There is no instance of the function template "ThreadPool:: enqueue" matching the parameter list compiled in vs2017

progschj commented 6 years ago

The following works fine for me:

#include "ThreadPool.h"

struct foo {
    int bar(int x) {
        return x*x;
    }
};

int main() {
    foo f;
    ThreadPool pool(1);
    auto result = pool.enqueue(&foo::bar, &f, 4); // (function pointer, this pointer, argument)
    return 0;   
}

in your second code the issue might not be with the member function but with passing the address of num to a function taking an int.

RemoteSensingFrank commented 6 years ago

yeah you are right! 👍 I change my code like

class test {
public:
    void TmpText()
    {
        ThreadPool tp(1);
        int num=9;
        auto result = tp.enqueue(&test::num, this, num);
        printf("%d\n", result.get());
    }

    int num(int i)
    {
        return i*i;
    }
};

and it's work fine for me thank a lot 👍