线程和进程的区别:
并行:
多线程之间如何进行同步或消息传递:
C++多线程的创建:
- 普通函数创建线程
- 通过类和对象创建线程
- Lambda表达式创建线程
- 带参的方式创建线程
- 带智能指针方式创建线程
- 通过类成员函数创建线程
线程调用方法与注意事项
普通函数创建线程 **↓
#include <iostream>
#include <thread>
using namespace std;
void print()
{
cout << "普通函数线程\t ID:"<<this_thread::get_id() << endl;
return;
}
int main1()
{
thread thred(print);
if (thred.joinable())
{
cout << "主线程已经调用join函数" <<endl;
}
else
{
cout << "主线程未调用join函数,进行调用" << endl;
thred.join();
}
system("pause");
return 0;
}
通过类和对象创建线程****↓**
#include <iostream>
#include <thread>
using namespace std;
class XX
{
public:
void operator()()
{
cout << "类对象线程\t ID:" << this_thread::get_id() << endl;
}
};
int main2()
{
thread thred1((XX()));
thred1.join();
XX xx;
thread thred2((xx));
thred2.join();
system("pause");
return 0;
}
Lambda表达式创建线程****↓**
#include <iostream>
#include <thread>
using namespace std;
int main3()
{
thread thred1([]() {1 > 2 ? 1 : 2; });
thred1.join();
system("pause");
return 0;
}
带参线程创建****↓**
#include <iostream>
#include <thread>
using namespace std;
void print4(int &number)
{
number = 10086;
cout << "number:" <<number <<endl;
}
int main4()
{
int numb = 1000;
thread thred1(print4,std::ref(numb));
thred1.join();
cout << "number:" << numb << endl;
system("pause");
return 0;
}
带智能指针的线程创建****↓**
#include <iostream>
#include <thread>
using namespace std;
void printf5( unique_ptr<int> ptr)
{
cout << "&ptr:" << &ptr << endl;
cout << "ptr:" << *ptr << endl;
}
int main5()
{
unique_ptr<int> ptr(new int(1000));
thread thred1(printf5, move(ptr));
thred1.join();
system("pause");
return 0;
}
通过类成员函数创建线程****↓**
#include <iostream>
#include <thread>
using namespace std;
class XXX
{
public:
void pornt(int &number)
{
cout << "number:" << number << endl;
}
};
int main()
{
int numb = 10086;
XXX xx;
thread thred(&XXX::pornt,xx, std::ref(numb));
thred.join();
system("pause");
return 0;
}