NO.1、普通函数充当线程函数创建线程
#include<thread>
#include<iostream>
using namespace std;
using namespace this_thread;
void print()
{
cout<<"线程处理函数启动"<<endl;
}
void test1()
{
thread t1(print); //用thread创建线程
t1.join(); //用join()线程处理函数
}
int main()
{
test1();
return 0;
}
NO.2、采用Lambda表达式充当线程处理函数
#include<thread>
#include<iostream>
using namespace std;
using namespace this_thread;
void test2()
{
thread t1([](){cout<<"Lambda表达式充当线程处理函数"<<endl;})
t1.join();
}
int main()
{
test2();
return 0;
}
NO.3、带参函数创建线程
3.1、普通叁数
#include<thread>
#include<iostream>
using namespace std;
using namespace this_thread;
void printDate(int num) //可以使用:comst int num
{
cout<<"id:"<<num<<endl;
}
void test3()
{
int num = 1;
thread t1(printDate,num); //第一个参数函数名,函数传参
t1.join();
}
int main()
{
test3();
return 0;
}
3.2、传引用
针对于引用变量 int &num 传叁问题,需要ref()包装引用作为转递的值
#include<thread>
#include<iostream>
using namespace std;
using namespace this_thread;
void printReference(int &num) //可以使用:const int &num
{
num = 100;
cout<<"子线程:"<<num<<endl;
}
void test4()
{
int num = 0;
thread t1(printReference,ref(num)); //需要ref():包装引用作为转递的值
t1.join();
}
int main()
{
test4();
return 0;
}
3.3、智能指针当函数
针对于unique_ptr<int> pty传叁问题,需要move()去传数据,在主线程得到数据是空的值
#include<thread>
#include<iostream>
using namespace std;
using namespace this_thread;
void printPtr(unique_ptr<int> pty)
{
cout<<"智能指针:"<<*ptr.get()<<endl;
}
void test5()
{
unique_ptr<int> ptr(new int(100));
cout<<"test5:"<<ptr.get()<<endl;
thread t1(printPtr,move(ptr)); //需要move()去传数据,在主线程得到数据是空的值
t1.join();
cout<<"得到空数据:"<<ptr.get()<<endl;
}
int main()
{
test5();
return 0;
}
NO.4、通过类中的成员函数去创建
4.1,仿函数形式:类名的方式调用
#include<thread>
#include<iostream>
using namespace std;
using namespace this_thread;
class Function
{
public:
void operator()()
{
cout<<"重载()"<<endl;
}
};
void test6()
{
//对像
Function object;
thread t1(object);
t1.join();
//匿名对像
thread t2((Function()));
t2.join();
}
int main()
{
test6();
return 0;
}
4.2、普通类中的成员函数
#include<thread>
#include<iostream>
using namespace std;
using namespace this_thread;
class MM
{
public:
void print(int &id)
{
cout<<"id:"<<id<<endl;
}
};
void test7()
{
MM mm;
int id = 1;
thread t1(&MM::print,mm,ref(id));
t1.join();
}
int main()
{
test7();
return 0;
}