1、创建多线程
#include <iostream>
#include <thread>
using namespace std;
void printx(int x)
{
cout << "thread_id = " << this_thread::get_id() << " x = " << x << endl;
}
int main()
{
const int n = 10;
thread th[n];
for (int i = 0; i < n; i++)
{
th[i] = thread(printx, i); //相当于给对象 th[i] 进行赋值初始化
}
for (int i = 0; i < n; i++)
{
th[i].join();
}
cout << "main exit" << endl;
return 0;
}
2、使多线程按创建顺序执行
#include <iostream>
#include <thread>
using namespace std;
void printx(int x)
{
cout << "thread_id = " << this_thread::get_id() << " x = " << x << endl;
}
int main()
{
const int n = 10;
thread th[n];
for (int i = 0; i < n; i++)
{
th[i] = thread(printx, i); //相当于给对象 th[i] 进行赋值初始化
th[i].join();
}
cout << "main exit" << endl;
return 0;
}