在多线程中调用函数的方法:
以函数名和函数参数作为输入对象来构造线程对象:t2 t4 t6 t7
通过lambda表达式调用函数,将函数作为lambda表达式的内容: t1 t3 t5
#include <iostream>
#include <thread>
#include <string>
void printAll(int a, int b, int c)
{
std::cout << a << " " << b << " " << c << std::endl;
}
void add(int a, int b, int&c)
{
c += a + b;
}
void printString(const std::string& info, const std::string& info2)
{
std::cout << "hello " << info << " " << info2 << std::endl;
}
void testThreadInit()
{
int a = 1;
int b = 2;
int c = 3;
std::cout << "t1: ";
std::thread t{[=]{printAll(a,b,c);}};//通过lambda表达式调用函数printALL,[=]表示将所需要参数按值拷贝
t.join();
std::cout << "t2: ";
std::thread t2(printAll,a,b,c);//通过线程对象的构造函数调用printALL,参数全部按值拷贝
t2.join();
std::cout << "t3: ";
std::thread t3([=,&c]{add(a,b,c);});//通过lambda表达式调用add,并将c以引用形式调用
t3.join();
printAll(a,b,c);
std::thread t4(add,a,b,std::ref(c));//通过构造函数调用add,通过ref(c)将c以&c的方式调用
t4.join();
std::cout << "t4: ";
printAll(a,b,c);
std::string abc("abc");
std::string def("def");
//t6的效率一定会比t5和t7的效率低,因为进行了一次string->const string的拷贝构造
std::thread t5([&]{printString(abc,def);});//[&]表示以引用方式调用lambda表达式中所有需要的对象
t5.join();
std::thread t6(printString, abc, def);
t6.join();
std::thread t7(printString, std::cref(abc),std::cref(def));//cref(abc)将abc以const& 的形式进行调用
t7.join();
}
int main()
{
testThreadInit();
return 0;
}
运行结果图下: