简体   繁体   English

如何将 std::thread 构造函数的目标 function 作为参数传递

[英]How to pass the target function of std::thread constructor as an argument

I can do this to start my thread:我可以这样做来启动我的线程:

int main_test() {
  // do something...
  return 0;
}

std::thread* myThread;

void myFunction() {
  myThread = new std::thread(main_test);
}

How do I pass main_test as an argument to myFunction , so the same function can be used to start the thread using different target functions?如何将main_test作为参数传递给myFunction ,因此可以使用相同的 function 使用不同的目标函数启动线程? What would the signature of myFunction be then?那么myFunction的签名会是什么?

I guess what I don't understand is how the templated version of the std::thread constructor is invoked with a specified type.我想我不明白的是如何使用指定类型调用std::thread构造函数的模板版本。

std::thread myThread;

The type of myThread is std::thread . myThread的类型是std::thread

 myThread = new std::thread(main_test);

new std::thread(main_test) returns std::thread* . new std::thread(main_test)返回std::thread* You cannot assign std::thread* into a std::thread .您不能将std::thread*分配给 std std::thread The program is ill-formed.该程序格式不正确。

Solution: There appears to be no reason to use dynamic allocation.解决方案:似乎没有理由使用动态分配。 Simply assign a temporary object like this:只需像这样分配一个临时 object :

myThread = std::thread(main_test);

How do I pass main_test as an argument to myFunction, so the same function can be used to start the thread using different target functions?如何将 main_test 作为参数传递给 myFunction,因此可以使用相同的 function 来使用不同的目标函数启动线程? What would the identity of myFunction be then?那么 myFunction 的身份是什么?

You can make your myFunction a template with exactly the same arguments as std::thread has, and forward everything.您可以将myFunction设为与std::thread具有完全相同的 arguments 的模板,然后转发所有内容。 Or, if you want to keep it simple, you can use a function pointer.或者,如果您想保持简单,可以使用 function 指针。

How do I pass main_test as an argument to myFunction, so the same function can be used to start the thread using different target functions?如何将 main_test 作为参数传递给 myFunction,因此可以使用相同的 function 来使用不同的目标函数启动线程?

You can pass the poiter to your function as an argument您可以将指针作为参数传递给您的 function

void myFunction(int (*func)()) {
myThread = new std::thread(func);
}

int callSelector(int someCriteria)
{
    if (someCriteria == 0) {
        myFunction(main_test1);
    }
    else {
        myFunction(main_test2);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM