gpt4 book ai didi

c++ - 将多个参数从另一个类传递给线程函数

转载 作者:太空宇宙 更新时间:2023-11-04 16:08:58 25 4
gpt4 key购买 nike

假设我有一个类:

class This
{
void that(int a, int b);
};

在我的主函数中,我需要在一个线程中启动“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.
}

我搜索过,但只找到了如何将参数传递给线程,以及如何在线程中运行另一个类的函数,但不是两者!

正确的做法是什么?

最佳答案

为了在另一个线程中运行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();

关于c++ - 将多个参数从另一个类传递给线程函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30894399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com