参考
1.环境配置
环境:Windows10
VScode
配置:C++11 thread 在 Windows 系统中无法使用问题解决_地球被支点撬走啦的博客-优快云博客
2.简单使用
多线程,也就是多个函数同步运行。首先我们先来定义两个函数。
头文件和两个函数如下:
#include <iostream>
#include "mingw.thread.h"
#include <windows.h>
using namespace std;
void thread_1()
{
for(int i = 0; i < 5; i++)
{
cout<<"子线程1"<<endl;
Sleep(1000);
}
}
void thread_2()
{
for(int i = 0; i < 5; i++)
{
cout<<"子线程2"<<endl;
Sleep(1000);
}
}
Sleep函数定义在<windows.h>中,它的使用为的是更清晰地显示两个线程。
下面是主函数:
int main(int argc, char *argv[])
{
cout << "主线程" << endl;
thread first(thread_1); // 添加第一个线程
cout << "#" << endl;
thread second(thread_2); // 添加第二个线程
cout << "##" << endl;
first.join(); // 定义线程1是否阻塞
cout << "###" << endl;
second.join(); // 定义线程2是否阻塞
cout << "####" << endl;
return 0;
}
值得注意的是
thread first(thread_1); // 添加第一个线程
这里不只是声明一个对象,线程从这里就已经启动了。它会自动到下方的代码寻找它是否阻塞主线程的——join()代表阻塞,detach()代表不阻塞。这些“#”目的是为了看清代码的运行。
3.一些探讨
结果如下:
主线程
#
子线程1
##
子线程2
子线程1
子线程2
子线程1
子线程2
子线程1
子线程2
子线程2
子线程1
###
####
可以看到“###”和"####"直到最后才输出到输出流上,这说明 thread first(thread_1) 会跳过中间主线程代码,直接到下方寻找定义是否阻塞的代码 first.join() 。"#"和“##”的位置也同样可以说明一些问题。