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

标签 c++ multithreading

假设我有一个类:

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/

相关文章:

c - Linux 内核互斥量

c++ - 使用 csparse : cs_cholsol 求解简单的稀疏线性方程组

c++ - Windows XP 及以上版本中的 GetwindowoffsetEx

c++ - 为什么单向链表的 Next() 操作要用临界区保护?

c++ - 使用 Lua 的游戏引擎多线程

windows - 我应该为 RTSP 客户端创建一个新线程还是只使用媒体基础中的自定义 IMFMediaSource

c++ - shared_from_this() 返回 std::shared_ptr<const X>,而不是 std::shared_ptr<X>

c++ - Qt 多线程信号和槽行为的问题

c# - C#-OutOfMemoryException将列表保存在JSON文件中

ios - 如何判断当前线程是否创建为 NSThread?