说我有课:
class This
{
void that(int a, int b);
};
在我的main函数中,我需要在一个线程中启动'that',然后传递2个参数。 这就是我所拥有的:
void main()
{
This t;
t.that(1,2); //works unthreaded.
std::thread test(t.that(1,2)); // Does not compile. 'evaluates to a function taking 0 arguments'
std::thread test2(&This::that, std::ref(t), 1, 2); //runs, but crashes with a Debug error.
}
我已经搜索过,但是只找到了如何将参数传递给线程,以及如何从线程中的另一个类运行函数,但不是两者都有!
这样做的正确方法是什么?
答案 0 :(得分:3)
为了在另一个线程中运行This
,您必须复制或确保只要另一个线程正在运行它仍然有效。尝试其中之一:
参考的
This t;
std::thread test([&]() {
t.that(1,2); // this is the t from the calling function
});
// this is important as t will be destroyed soon
test.join();
复制的
This t;
std::thread test([=]() {
t.that(1,2); // t is a copy of the calling function's t
});
// still important, but does not have to be in this function any more
test.join();
动态分配
auto t = std::make_shared<This>();
std::thread(test[=]() {
t->that(1,2); // t is shared with the calling function
});
// You still have to join eventually, but does not have to be in this function
test.join();
答案 1 :(得分:2)
对象t
在main()
函数结束时被销毁,但该线程在此之后运行了一段时间。它会导致未定义的行为。在退出程序之前加入所有线程通常也是一个好主意。把它放在最后:
test2.join();
答案 2 :(得分:0)
This ::它不会引用This作为它的第一个参数。
我认为你想要做的更像是
auto t = std::make_shared<This>();
std::thread test2{ [t](int a, int b) { t->that(a, b); }, 1, 2 };