C++ 函子的正确使用STL螺纹
我很难理解函数对象的正确用法作为C ++ STL中的线程例程。从我的理解来看,函子的好处之一是对象实例可以维护状态。有时我希望一个或多个线程运行一些例程并计算一些结果。然后,我加入线程后,我从对象中查询这些结果。我正在尝试使用C ++ STL线程进行操作,并遇到一些问题。问题似乎是由于C ++ STL线程制作了我的对象的副本,因此我不确定在加入线程时如何检查结果。这是代码的片段:
#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,但它返回零。如何使用状态实例化对象,让线程在该对象中运行例程,然后在线程完成后查询该对象的状态?
谢谢, 缺口
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您通过Value通过时,您会制作副本。因此,您可以通过参考包装器通过参考:
或通过指针传递:
在这两种情况下,您都必须确保对象寿命足够长。
When you pass by value you make a copy. So you can pass by reference through reference wrapper:
or pass by pointer:
in both cases you have to make sure that object lifetime is long enough.
不要复制,而是将线程绑定到引用:
Don't make a copy, but instead bind the thread to a reference: