我是 C++11 线程的新手,正在尝试使用类的成员函数在并发线程中运行。
在回答我之前的问题时,我收到了以下建议:
std::thread t1(&SomeClass::threadFunction, *this, arg1, arg2);
我实现了上述建议。它消除了我遇到的编译错误,但引入了运行时错误。在另一个问题中,我收到了删除所有复制机制的建议。其实我不想复制数据,因为代码是做有限元分析的,需要很大的内存。
有什么办法可以做到这一点吗?
header类似下面
SomeClass {
vector<int*> someVariable;
public:
~SomeClass();
void threadedMethod(bool, bool); // Inside this method the
// member vector 'someVariable' is used.
void someMethod(); // In this function the threadedMethod has
// been used twice to make 2 different thread
};
someMethod 的实现是,
void SomeClass::someMethod() {
thread t1(&SomeClass::threadedMethod, *this, arg1, arg2);
thread t2(&SomeClass::threadedMethod, *this, arg1, arg2);
t2.join();
t1.join();
}
析构函数类似下面,
SomeClass::~SomeClass() {
int count = someVariable.size();
for(int i=0; i < count; i++) {
delete someVariable[i];
}
}
threadMethod 访问变量。这些操作是数据并行的。结果,没有线程会写入同一个内存块。再次,读写内存不同。因为我认为我不需要任何类型的锁。
如您所见,我正在使用 *this
并且这会导致大量复制。我真的需要避免它。任何人都可以建议任何其他方式让我避免复制吗?
如果您需要更多解释,请告诉我。如果在我的能力范围内,我会尽量详细说明。
我使用的是装有 OS X 10.8.3 的 Intel Mac。我在 Xcode 4.6.1 上编码。编译器是 Apple LLVM 4.2(默认编译器)。
最佳答案
参数按值传递给std::thread
的构造函数。因此,这个声明:
std::thread t1(&SomeClass::threadFunction, *this, arg1, arg2);
// ^^^^^
触发 *this
的拷贝,这不是您想要的。但是,std::thread
也可以接受一个指针,指向调用成员函数的对象,就像 std::bind
.
因此,通过将 this
(而不是 *this
)作为参数传递,它是指针 - 而不是指向的对象 -这将按值传递并最终被复制。如您所愿,这将不会触发 SomeClass
的复制构造。
因此,你应该改写上面的语句如下:
std::thread t1(&SomeClass::threadFunction, this, arg1, arg2);
// ^^^^
关于c++ - 有什么方法可以使用类的成员函数在并发线程中运行而无需在 C++11 中传递 *this 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15736144/