this_thread::get_id():获取当前线程的id
1.类对象和仿函数创建线程
#include <iostream>
#include <thread>
#include <mutex>
#include <fstream>
#include <deque>
#include <condition_variable>
#include <future>
#include <windows.h>
using namespace std;
class A
{
public:
A() {};
~A() {};
//重载()方法
void operator()()
{
cout << "子线程" << endl;
}
};
int main()
{
//类对象操作方法
A a;
thread test(a);
test.join();
//A();//仿函数操作方法
thread test1((A()));
test1.join();
cout << "父线程" << endl;
return 0;
}
2.lamda表达式创建线程
int main()
{
thread test([]() { cout << "子线程" << endl; });
test.join();
cout << "父线程" << endl;
return 0;
}
3.带参数的创建线程
void A(int& num)
{
num += 10;
cout << "子线程 A is:" << num << endl;
}
void B(int num)
{
cout << "子线程 B is:" << num << endl;
}
int main()
{
//传引用
int a = 10;
thread test(A,ref(a));
test.join();
//传值
int b = 10;
thread testB(B, b);
testB.join();
cout << "父线程" << endl;
return 0;
}
4.智能指针创建方式
void A(unique_ptr<int> ptr)
{
cout << "子线程:" << *ptr<< endl;
}
void B(shared_ptr<int> ptr)
{
cout << "子线程:" << *ptr << endl;
}
int main()
{
unique_ptr<int> ptr(new int(100));
thread testA(A, move(ptr));
testA.join();
shared_ptr<int> ptrB(new int(100));
thread testB(B, ptrB);
testB.join();
cout << "父线程" << endl;
return 0;
}
5.类成员函数创建线程
class A
{
public:
A() {};
~A() {};
public:
void print(int& num)
{
cout << "子线程:" <<num<< endl;
}
};
int main()
{
A a;
int num = 10;
thread test(&A::print,a,ref(num));
test.join();
cout << "父线程" << endl;
return 0;
}