Associate packaged_task and thread in C++

933 views Asked by At

all

I have a class:

class someClass
{
 public:
    vector<int> someOperation(int start, int end)
    {
         // do something...
    }
}

and a main function:

int main()
{
    someClass obj;

    std::packaged_task<vector<int>(int, int)> task(&someClass::someOperation);

    std::thread t1 = std::thread(std::move(task), &obj, 0, 200);   // Error happens here
    std::thread t2 = std::thread(std::move(task), &obj, 201, 400);
    std::thread t3 = std::thread(std::move(task), &obj, 401, 600);

    t1.join();
    t2.join();
    t3.join();

    return 0;
}

I expect this code can create three threads that run same operation on different part of a piece of data. However, in the definition of thread t1, compiler pops following error:

error C2046: term does not evaluate to a function taking 3 arguments

May I know what am I wrong, and how can I do it right?

Many thanks in advance.

Long

1

There are 1 answers

0
R. Martinho Fernandes On

The problem is that &someClass::someOperation cannot be used without an instance of someClass. You realise that because you do pass one such instance into the thread constructor, but forgot it in the packaged_task signature:

std::packaged_task<vector<int>(someClass*, int, int)> task(&someClass::someOperation);

Another issue is that you are trying to move task into three different places. That won't work: after it moves once, the task won't be valid anymore, and moving it into the other threads won't do what you expect. You need three different tasks.