#include<cstdio>
#include<cstdlib>
#include<iostream>
#include <thread>
using namespace std;
class A
{
public:
//类型转换构造函数
A(int i) :m_i(i)
{
cout << "构造函数执行"<< endl;
}
A(const A & a) :m_i(a.m_i)
{
cout << "拷贝构造函数执行" << endl;
}
~A()
{
cout << "析构函数执行" << endl;
}
private:
int m_i;
};
void myprint(const int i ,const A& mybuf)
{
//打印对象的地址
cout << &mybuf << endl;
}
int main()
{
int i = 7;
int j = 9;
//j 转换成A对象
thread myobj(myprint,i,j);
//等待myprint()执行完
myobj.join();//加入,汇合,说白了就是阻塞,让主线程等待子线程执行完毕,然后子线程和主线程汇合
cout << "I love china !" << endl;
return 0;
}
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include <thread>
using namespace std;
class A
{
public:
//类型转换构造函数
A(int i) :m_i(i)
{
cout << "构造函数执行"<< endl;
}
A(const A & a) :m_i(a.m_i)
{
cout << "拷贝构造函数执行" << endl;
}
~A()
{
cout << "析构函数执行" << endl;
}
private:
int m_i;
};
void myprint(const int i ,const A& mybuf)
{
//打印对象的地址
cout << &mybuf << endl;
}
int main()
{
int i = 7;
int j = 9;
//j 转换成A对象
thread myobj(myprint,i,A(j));
myobj.detach();//不建这样使用,不用等待,有可能,主线程先完成,导致 int i ,j A a 临时变量会消失
等待myprint()执行完
//if (myobj.joinable)
//{
// myobj.join();//加入,汇合,说白了就是阻塞,让主线程等待子线程执行完毕,然后子线程和主线程汇合
//}
cout << "I love china !" << endl;
return 0;
}
//使用myobj.detach() 注意总结:
//(a)若传递int 这种简单类型参数,建议都是值传递,不要用引用,防止节外生枝
//(b)如果传递类对象,避免隐式类型转换。全疗都在创建线程这一行就构建出临时对象来,然后在函数参数,用引用来接,否则要一次构造,二次拷贝
//总结:建议不使用detch(),只使用join().这样就不存在局部变量失效,导致线程对内存的非法引用问题
//线程ID
//c++ 标准库 std::this_thread::get_id()来获取
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include <thread>
using namespace std;
class A
{
public:
//类型转换构造函数
A(int i) :m_i(i)
{
cout << "构造函数执行"<< this << "threadid =" << std::this_thread::get_id() << endl;
}
A(const A & a) :m_i(a.m_i)
{
cout << "拷贝构造函数执行" << this << "threadid =" << std::this_thread::get_id() << endl;
}
~A()
{
cout << "析构函数执行" << this << "threadid =" << std::this_thread::get_id() << endl;
}
private:
int m_i;
};
void myprint(const A& mybuf)
{
//打印对象的地址
cout << "myprint" << &mybuf << "threadid =" << std::this_thread::get_id() << endl;
}
int main()
{
//主线程ID
cout << "主线程iD:" << "threadid =" << std::this_thread::get_id() << endl;
int j = 9;
//j 转换成A对象,A对象是在,子线程中构造A类对象
thread myobj(myprint,j);//子线程中构造A类对象(重点)
thread myobj(myprint, A(j));//A对象,是在主线程构造A类对象,(重点)
//等待myprint()执行完
if (myobj.joinable())
{
myobj.join();//加入,汇合,说白了就是阻塞,让主线程等待子线程执行完毕,然后子线程和主线程汇合
}
cout << "I love china !" << endl;
return 0;
}