1、包含 thread头文件,先看一段正常代码:
#include <iostream>
using namespace std;
static mutex ut;
void fun1(int num)
{
cout << "这是序列1 " << "应该首先执行" << endl;
cout << "第一个序列已执行完" << endl;
}
void fun2()
{
cout << "这是序列2 " << "后面执行" << endl;
cout << "第二个序列已执行完" << endl;
}
int main()
{
cout << "这是主函数开始" << endl;
fun1();
fun2();
cout << "这是主函数结束" << endl;
}
2、添加头文件thread,创建多线程
#include <iostream>
#include<thread>
using namespace std;
static mutex ut;
void fun1(int num)
{
cout << "这是序列1 " << "应该首先执行" << endl;
cout << "第一个序列已执行完" << endl;
}
void fun2()
{
cout << "这是序列2 " << "后面执行" << endl;
cout << "第二个序列已执行完" << endl;
}
int main()
{
cout << "这是主函数开始" << endl;
thread th1(fun1, 2); //创建线程1
thread th2(fun2);//创建线程2
th1.join();//线程1加入 顺序1
th2.join();//线程1加入 顺序2
//th1.detach(); //detach并行执行
//th2.detach();
cout << "这是主函数结束" << endl;
}
join():按顺序执行
detach( ):并行执行,放飞自我。
3、载入头文件加锁,让其阻塞,进行顺序执行(可以使用多个锁,并发执行未占用相同资源的线程)
#include <iostream>
#include<thread>
#include<mutex>
using namespace std;
static mutex ut;
void fun1(int num)
{
ut.lock();
cout << "这是序列1 " << "应该首先执行" << endl;
cout << "第一个序列已执行完" << endl;
ut.unlock();
}
void fun2()
{
ut.lock();
cout << "这是序列2 " << "后面执行" << endl;
cout << "第二个序列已执行完" << endl;
ut.unlock();
}
int main()
{
cout << "这是主函数开始" << endl;
thread th1(fun1, 2);
thread th2(fun2);
th1.detach();
th2.detach();
cout << "这是主函数结束" << endl;
}
又按顺序执行了
-----——————————————————我是分割线——————————————------
对于Qt的多线程使用
1、帮助手册会给各种成员函数的使用方法,我们将必要的几个
创建的线程类需要继承Qthread类(简单易用的方式),必须重写run()函数。
大概一个使用过程如下:
1、继承QThread创建子类A
{
//下面的函数都是只在该线程内有效
sleep(多少秒) //睡眠
msleep(多少毫秒)
}
2、子类A创建线程对象B
3、线程将执行完通知延迟销毁线程对象(下一个循环事件event到来时)
run( )函数return后就会自动发动finished信号,后面再进入重新start()
在finished 的信号槽中用wait()阻塞,wait返回后线程才真正finish
connect(&B, &QThread::finished, A, &QObject::deleteLater);
4、 B.start() //开始运行该线程A实例对象B
5、线程退出
一般调用quit()函数之后可以紧接着调用wait()函数确保线程退出。