QT多线程使用互斥体

这篇博客介绍了一个使用QT多线程和互斥体来保护用户类私有数据的操作示例。通过在三个线程中并行执行任务,并利用互斥体确保数据一致性。如果移除互斥体,输出将会出现乱序。详细内容包括头文件test.h的定义和主函数main.cpp的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过三个线程对用户类私有数据进行操作,使用互斥体进行资源保护,因为简单,所以所有类成员函数都定义为了内联函数,若注释掉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;
}

运行结果:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值