// ConsoleApplication2.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<thread>
using namespace std;
void myPrint();
void firstMesod() {
thread mythread(myPrint);//创建线程,从线程起点开始执行
//mythread.join();//join让主线程等待子线程执行完毕,是一个阻塞,子线程执行完毕,主线程就继续往后走
//detach():传统多线程程序主线程要等待子线程执行完毕,然后自己再最后退出。子线程不和主线程汇合
//为什么引入detach():我们创建了很多子线程,让主线程逐个等待子线程结束,这种编程方法不太好,所以引入了detach()
// mythread.detach();//子线程会驻留在后台运行(守护线程),当这个子线程执行完成后,由运行时库负责清理该线程相关的资源。一旦使用detech就不能用join了
//(1.4)joinable():判断是否可以成功使用join()或者detach()的,用过join和detach就不能用了
if (mythread.joinable()) {
mythread.join();
cout << "I love China!" << endl;//主线程在执行
}
else {
cout << "不可使用joinable()" << endl;//主线程在执行
}
}
void myPrint() {
cout << "线程开始从一个函数运行了" << endl;
cout << "线程运行结束了" << endl;
cout << "线程开始从一个函数运行了" << endl;
cout << "线程运行结束了" << endl;
cout << "线程开始从一个函数运行了" << endl;
cout << "线程开始从一个函数运行了" << endl;
cout << "线程运行结束了" << endl;
cout << "线程开始从一个函数运行了" << endl;
cout << "线程运行结束了" << endl;
cout << "线程开始从一个函数运行了" << endl;
cout << "线程运行结束了" << endl;
cout << "线程运行结束了" << endl;
}
class TA {
public:
int& ai;//一定要注意如果这么写的话从主线程中传过来的参数,一定要在主线程中使用join而不是detach因为一旦和主线程脱钩引用指向的数据就在主线程结束时被销毁了
TA(int& i) :ai(i) {
cout << "TA构造函数被执行" << endl;
}
TA(const TA& ta) :ai(ta.ai) {
cout << "TA拷贝构造函数被执行" << endl;
}
~TA() {
cout << "TA析构函数被执行" << endl;
}
void operator()() {//必须重写()才能创建线程
cout << "ai = " << ai << endl;
cout << "ai = " << ai << endl;
cout << "ai = " << ai << endl;
cout << "ai = " << ai << endl;
cout << "ai = " << ai << endl;
cout << "ai = " << ai << endl;
cout << "ai = " << ai << endl;
}
void show() {
//cout << "线程开始从一个函数运行了" << endl;
...
//cout << "线程运行结束了" << endl;
cout << "ai = " <<ai<< endl;
cout << "ai = " << ai << endl;
cout << "ai = " << ai << endl;
cout << "ai = " << ai << endl;
cout << "ai = " << ai << endl;
cout << "ai = " << ai << endl;
cout << "ai = " << ai << endl;
}
};
void secondMethod() {
//第二种线程创建手法:
int myi = 6;
TA ta(myi);//myi是主线程的局部变量,形参是引用类型,当主线程执行完之后myi就被销毁了,所以子线程如果还在执行那么就打印不出来myi
thread mytobj(ta);//ta是可调用对象,一定要重载()变成一个可调用对象
mytobj.join();
cout << "I Love China" << endl;
//主线程结束了ta不在了怎么子线程还能调用operator?因为这个对象是被复制到线程中去了,所以执行完主线程后ta会被销毁,但是复制的TA对象依旧存在
//但是没有引用和指针是怎么复制过去的呢
}
void thirdMethod() {
auto mylamthread = [] {
cout << "我的线程开始执行了" << endl;
};
thread mytobj(mylamthread);
mytobj.join();
cout << "main" << endl;
}
int main()
{
firstMesod();
secondMethod();
thirdMethod();
return 0;
}