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