为C ++ STL线程正确使用functor [英] correct use of functor for C++ STL thread

查看:121
本文介绍了为C ++ STL线程正确使用functor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解功能对象作为C ++ STL中的线程例程的正确用法时遇到了一些困难.根据我的理解,函子的好处之一是对象实例可以维护状态.有时候,我希望一个或多个线程运行一些例程并计算一些结果.然后,我在加入线程后从对象查询那些结果.我正在尝试对C ++ STL线程执行相同的操作,并遇到一些问题.看来问题出在C ++ STL线程复制了我的对象,因此我不确定加入线程时应该如何检查结果.这是代码段:

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;
}

上面的例子只是我遇到的问题的简单再现.我希望worker.get_value()返回13但它返回零.我该如何实例化具有状态的对象,让线程在该对象中运行例程,然后在线程完成后查询该对象的状态?

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?

谢谢, 尼克

推荐答案

当您按值传递时,将进行复制.因此,您可以通过引用包装传递引用:

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

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

或通过指针传递:

thread thread(&worker, 13);

在两种情况下,您都必须确保对象生存期足够长.

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

这篇关于为C ++ STL线程正确使用functor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆