progschj / ThreadPool

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

How to pass multi parameters to pool.enqueue? #69

Closed monchin closed 4 years ago

monchin commented 4 years ago

Hello, I looked example.cpp and found that the example pass i to pool.enqueue. But in fact, I would like to use this pool to run a function with multi parameters. The code seems a little confusing to me, so l'd like to ask how to pass multi parameters to pool.enqueue?

wilx commented 4 years ago

The ThreadPool::enqueue() function uses template parameter pack so it should be able to handle any number of function parameters.

monchin commented 4 years ago

The ThreadPool::enqueue() function uses template parameter pack so it should be able to handle any number of function parameters.

Thank you! But I'm not quite familiar with C++, so maybe the question would be too naive. In the example, the code is

            pool.enqueue([i] {
                std::cout << "hello " << i << std::endl;
                std::this_thread::sleep_for(std::chrono::seconds(1));
                std::cout << "world " << i << std::endl;
                return i*i;
            }

I guess the parameters should be passed in [] just as [i] in the example, and if I've already written a function fun(int a, float b), I would call the fun in {}. But it can't pass the compilation. So if I have a function:

 int fun(int a, float b){
    if (float(a)>b) return 1;
    else return 0;
}

how to call fun to pool.enqueue? Would you please give a simple example? Thank you!

fogti commented 4 years ago

Maybe:

auto x = pool.enqueue([a, b] {
    if (float(a)>b) return 1;
    else return 0;
});

or:

auto x = pool.enqueue([](int a, float b) {
    if (float(a)>b) return 1;
    else return 0;
}, a, b);

Later, when you want to retrieve the return value of the function:

auto result = x.get();
monchin commented 4 years ago

Maybe:

auto x = pool.enqueue([a, b] {
    if (float(a)>b) return 1;
    else return 0;
});

or:

auto x = pool.enqueue([](int a, float b) {
    if (float(a)>b) return 1;
    else return 0;
}, a, b);

Later, when you want to retrieve the return value of the function:

auto result = x.get();

Thank you very much! So in this pool, we can't write a function and call it in {}, am I right?

fogti commented 4 years ago

So in this pool, we can't write a function and call it in {}, am I right?

I don't think so.

another alternative:

int fun(int a, float b){
    if (float(a)>b) return 1;
    else return 0;
}

    /// later, inside another function
    auto x = pool.enqueue(fun, a, b);
monchin commented 4 years ago

I don't think so.

another alternative:

int fun(int a, float b){
    if (float(a)>b) return 1;
    else return 0;
}

    /// later, inside another function
    auto x = pool.enqueue(fun, a, b);

This solution works! Thank you very much!!