std::thread支持为线程传入参数,且支持任意类型、任意数目的参数。参数传入方式如下所示:
#include <iostream>
#include <string>
#include <vector>
#include <thread>
void fun(int32_t n, std::string str, std::vector<std::string> vec)
{
std::cout << "method one: thread start" << std::endl;
std::cout << "first input parameter is: " << n << std::endl;
std::cout << "second input parameter is: " << str << std::endl;
std::cout << "third input parameter is: [";
for(std::vector<std::string>::const_iterator it = vec.begin(); it != vec.end(); it++)
{
std::cout << *it << ", ";
}
std::cout << "]" << std::endl;
std::cout << "method one: thread stop" << std::endl;
}
class run
{
public:
void operator()(int32_t n, std::string str, std::vector<std::string> vec)
{
std::cout << "method two: thread start" << std::endl;
std::cout << "first input parameter is: " << n << std::endl;
std::cout << "second input parameter is: " << str << std::endl;
std::cout << "third input parameter is: [";
for(std::vector<std::string>::const_iterator it = vec.begin(); it != vec.end(); it++)
{
std::cout << *it << ", ";
}
std::cout << "]" << std::endl;
std::cout << "method two: thread stop" << std::endl;
}
};
int32_t main()
{
// one method of launching thread
std::thread t_1(fun, 10, "test one", std::vector<std::string>(3, "one"));
std::cout << "method one: start test thread" << std::endl;
t_1.join();
std::cout << "method one: over" << std::endl << std::endl;
// the other method of launching thread
run r;
std::thread t_2(std::ref(r), 20, "test two", std::vector<std::string>(3, "two"));
std::cout << "method two: start test thread" << std::endl;
t_2.join();
std::cout << "method two: over" << std::endl;
return 0;
}
输出为:
method one: start test thread
method one: thread start
first input parameter is: 10
second input parameter is: test one
third input parameter is: [one, one, one, ]
method one: thread stop
method one: over
method two: start test thread
method two: thread start
first input parameter is: 20
second input parameter is: test two
third input parameter is: [two, two, two, ]
method two: thread stop
method two: over