C++ 将多个参数传递给 std::thread

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20340750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:04:00  来源:igfitidea点击:

Pass multiple arguments into std::thread

c++multithreadingc++11

提问by turtlesoup

I'm asking the <thread>library in C++11 standard.

我问的<thread>是 C++11 标准中的库。

Say you have a function like:

假设你有一个类似的功能:

void func1(int a, int b, ObjA c, ObjB d){
    //blahblah implementation
}

int main(int argc, char* argv[]){
    std::thread(func1, /*what do do here??*/);
}

How do you pass in all of those arguments into the thread? I tried listing the arguments like:

您如何将所有这些参数传递到线程中?我尝试列出如下参数:

std::thread(func1, a,b,c,d);

But it complains that there's no such constructor. One way to get around this is defining a struct to package the arguments, but is there another way to do this?

但它抱怨没有这样的构造函数。解决这个问题的一种方法是定义一个结构来打包参数,但还有另一种方法可以做到这一点吗?

回答by aaronman

You literally just pass them in std::thread(func1,a,b,c,d);that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminateis called. You could std::joinor std::detachit before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach.

std::thread(func1,a,b,c,d);如果对象存在,您实际上只是将它们传递给应该已编译的对象,但由于另一个原因,这是错误的。由于没有创建对象,您无法加入或分离线程,程序将无法正常工作。由于它是临时的,因此立即调用析构函数,因为尚未std::terminate调用线程未连接或分离。你可以在 temp 被破坏之前std::join或者std::detach它,比如std::thread(func1,a,b,c,d).join();//or detach.

This is how it should be done.

这是应该如何做的。

std::thread t(func1,a,b,c,d);
t.join();  

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

如果您不知道加入和分离之间的区别,您也可以分离线程,阅读线程。

回答by Ji?í

Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.

有同样的问题。我正在传递自定义类的非常量引用,并且构造函数抱怨(一些元组模板错误)。用指针替换了引用并且它起作用了。

回答by pixelpax

If you're getting this, you may have forgotten to put #include <thread>at the beginning of your file. OP's signature seems like it should work.

如果你得到这个,你可能忘记把它放在#include <thread>文件的开头。OP 的签名似乎应该可以工作。