correct use of functor for C++ STL thread

若如初见. 提交于 2019-12-10 15:39:09

问题


I'm having some difficulty understanding the correct usage of a functional object as a thread routine in C++ STL. From my understanding, one of the benefits of a functor is that the object instance can maintain state. There are times when I want one or more threads to run some routine and compute some result. I then query those results from the objects after I have joined the threads. I'm trying to do the same with C++ STL threads and running into some problems. It appears the problem stems from the fact that the C++ STL thread makes a copy of my object and thus I'm not sure how I'm supposed to go about inspecting the results when I join the threads. Here's a snippet of the code:

#include <iostream>
#include <thread>

using namespace std;

class Worker
{
public:
    Worker() : _value(0)
    {
    }

    void operator()(unsigned int value);

    unsigned int get_value() {return this->_value;}

private:
    unsigned int _value;
};

void Worker::operator()(unsigned int value)
{
    this->_value = value;
}

int main()
{
    Worker worker;
    thread thread(worker, 13);
    thread.join();
    unsigned int value = worker.get_value();
    cout << "value: " << value << endl;
}

The above example is just a simple repro of the problem I'm running into. I would expect worker.get_value() to return 13 yet it's returning zero. How do I go about instantiating an object with state, having a thread run a routine in that object, and then query the state of that object after the thread has completed?

Thanks, Nick


回答1:


When you pass by value you make a copy. So you can pass by reference through reference wrapper:

thread thread(std::ref(worker), 13);

or pass by pointer:

thread thread(&worker, 13);

in both cases you have to make sure that object lifetime is long enough.




回答2:


Don't make a copy, but instead bind the thread to a reference:

thread thread(std::ref(worker), 13);
//            ^^^^^^^^


来源:https://stackoverflow.com/questions/42894629/correct-use-of-functor-for-c-stl-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!