QT多线程使用互斥体
来源:互联网 发布:mac怎么用u盘重装系统 编辑:程序博客网 时间:2024/05/01 18:52
通过三个线程对用户类私有数据进行操作,使用互斥体进行资源保护,因为简单,所以所有类成员函数都定义为了内联函数,若注释掉user::mreturn()函数中的互斥体,则乱序输出。
头文件 test.h
#ifndef TEST_H#define TEST_H#include <QDebug>#include <QThread>#include <QMutex>#include <QMutexLocker>#include <iostream>class user{private: int m_ia; QMutex mutex; //mutex一般都作为私有成员供QMutexLocker对象的构造函数使用public: user(){ m_ia=5; } ~user(){} void mreturn(int num,int j) //在mreturn()函数中进行 m_ia+=num 操作,j为调用次数 { QMutexLocker locker(&mutex); //使用互斥体锁住此函数,同一时刻只有一个线程可以使用此函数 m_ia += num; std::cout<<j<<" thread"; switch(num) { case -2:std::cout<<"one -2 ";break; case 3:std::cout<<"two +3 ";break; case 5:std::cout<<"three +5 ";break; } std::cout<<m_ia<<std::endl; return; }};class threadone : public QThread //线程one{private: user* ur;public: threadone(user* u){ ur = u; } threadone(){} ~threadone(){} void run() { int i=10; while(--i) //在线程中使用while,控制线程执行次数,也可以用flag标志位,通过外部控制 { ur->mreturn(-2,i); //线程one对m_ia-2 } }};class threadtwo : public QThread //线程two{private: user* ur;public: threadtwo(user* u){ ur = u; } threadtwo(){} ~threadtwo(){} void run() { int i=10; while(--i) //在线程中使用while,控制线程执行次数,也可以用flag标志位,通过外部控制 { ur->mreturn(3,i); //线程two对m_ia+3 } }};class threadthree : public QThread //线程three{private: user* ur;public: threadthree(user* u){ ur = u; } threadthree(){} ~threadthree(){} void run() { int i=10; while(--i) //在线程中使用while,控制线程执行次数,也可以用flag标志位,通过外部控制 { ur->mreturn(5,i); //线程three对m_ia+5 } }};#endif // TEST_H
主函数 main.cpp
#include <QtCore>#include <test.h>#include <windows.h>int main(int argc,char * argv[]){ user us; //用户类实例 threadone one(&us); //线程类实例 threadtwo two(&us); threadthree three(&us); one.start(); //开始线程 two.start(); three.start(); Sleep(2000); //延时2s,调用windows系统API,需加头文件windows.h one.terminate(); //结束线程one one.wait(); two.terminate(); //结束线程two two.wait(); three.terminate(); //结束线程three three.wait(); return 0;}
运行结果:
0 0
- QT多线程使用互斥体
- 正确使用Qt多线程
- Qt多线程使用
- 正确使用Qt多线程
- Qt中使用多线程
- 正确使用Qt多线程
- 正确使用Qt多线程
- QT多线程使用总结
- 正确使用Qt多线程
- Qt中多线程的使用
- QT 多线程服务器及数据库使用
- Qt 多线程两种使用方式不同
- Qt中多线程使用的一些感想
- Qt中多线程的一种使用
- qt,使用moveToThread函数实现多线程
- Qt使用多线程的一些心得
- Qt/C++ Qt多线程竟然不能使用VC的套路
- Qt多线程
- VS2012下X64平台嵌入汇编程序
- 设计模式学习笔记——策略模式
- Largest Rectangle in a Histogram
- 空汽水瓶换汽水问题
- 信源编码第二次作业
- QT多线程使用互斥体
- STM32 —— 多路DAC(输出电压和正弦波)
- keil中的printf函数显示结果
- 递归算法---全排列
- Android Activity生命周期--应知应会
- slua 1.3.1 vs2017 build file
- 记录下 刚开的博客
- 7.Draftjs 学习笔记-StateToHtml
- (java)leetcode-22