#include

1 detach

脱离当前主线程,*执行,乱序;

2 join()

等待模式,执行完再执行下一个

3 std::this_thread::get_id()

获取当前线程编号

4 std::thread::hardware_concurrency()

检测CPU有多少个核心

1 detach

脱离当前主线程,*执行,乱序;

2 join()

等待模式,执行完再执行下一个

 #include <iostream>
#include <thread> void run(int num)
{
std::cout << "hello world" << num << std::endl;
} void main()
{
std::thread *p[]; for (int i = ; i < ; i++)
{
p[i] = new std::thread(run, i);//循环创建线程
//p[i]->join();//等待模式,执行完再执行下一个
p[i]->detach();//脱离当前主线程,*执行,乱序;
} system("pause");
}

1 join()

等待模式,执行完再执行下一个

2 std::this_thread::get_id()

获取当前线程编号

3 std::thread::hardware_concurrency()

检测CPU有多少个核心

 #include <iostream>
#include <thread>
#include <windows.h> void msg()
{
MessageBoxA(, "对话框内容", "对话框标题", );//弹出对话框
} void main()
{
auto n = std::thread::hardware_concurrency();//检测CPU有多少个核心
std::cout << n << std::endl; std::cout << "thread=" << std::this_thread::get_id() << std::endl;//获取当前线程编号 std::thread thread1(msg);//创建多线程
std::thread thread2(msg); thread1.join();//开始执行,同时弹出2个对话框
thread2.join(); system("pause");
}

std::vector<std::thread *>threads;//创建一个数组,数组的元素数据类型是std::thread *

threads.push_back(new std::thread(msg));//创建线程,并添加到数组

 #include <iostream>
#include <thread>
#include <vector>
#include <windows.h> void msg()
{
MessageBoxA(, "对话框内容", "对话框标题", );//弹出对话框
} void main()
{
std::vector<std::thread *>threads;//创建一个数组,数组的元素数据类型是std::thread * for (int i = ; i < ; i++)
{
threads.push_back(new std::thread(msg));//创建线程,并添加到数组
} for (auto th : threads)//遍历数组
{
th->join();//执行数组中的线程
} system("pause");
}

threads.push_back(new std::thread(msgA, i));//创建线程,并添加到数组,传入参数i,进行通信

 #include <iostream>
#include <thread>
#include <vector>
#include <windows.h> void msgA(int num)
{
std::cout << std::this_thread::get_id() << " num=" << num << std::endl;//获取当前线程编号
MessageBoxA(, "对话框内容", "对话框标题", );//弹出对话框
} void main()
{
std::vector<std::thread *>threads;//创建一个数组,数组的元素数据类型是std::thread * for (int i = ; i < ; i++)
{
threads.push_back(new std::thread(msgA, i));//创建线程,并添加到数组,传入参数i,进行通信
} for (auto th : threads)//遍历数组
{
th->join();//执行数组中的线程
} system("pause");
}
上一篇:Mac 配置adb环境变量(为了开Appium)亲测


下一篇:redis入门指南-附录B