将多个参数传递给std :: thread [英] Pass multiple arguments into std::thread

查看:2399
本文介绍了将多个参数传递给std :: thread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求C ++ 11标准中的< thread> 库。

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

假设你有一个函数:

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?

推荐答案

你确实只是在 std :: thread(func1,a,b,c, d); 应该已经编译,如果对象存在,但它是错误的另一个原因。由于没有创建对象,因此无法加入或分离线程,程序将无法正常工作。因为它是一个临时的析构函数被立即调用,因为线程没有连接或分离, std :: terminate 被调用。你可以在临时被销毁之前加入或分离它,例如 std :: thread(func1,a,b,c,d).join(); //或detach

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::terminate is called. You could join or detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

这是应该怎么做的。

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.

这篇关于将多个参数传递给std :: thread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆