通过三个线程对用户类私有数据进行操作,使用互斥体进行资源保护,因为简单,所以所有类成员函数都定义为了内联函数,若注释掉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;
public:
user(){ m_ia=5; }
~user(){}
void mreturn(int num,int 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
{
private:
user* ur;
public:
threadone(user* u){ ur = u; }
threadone(){}
~threadone(){}
void run()
{
int i=10;
while(--i)
{
ur->mreturn(-2,i);
}
}
};
class threadtwo : public QThread
{
private:
user* ur;
public:
threadtwo(user* u){ ur = u; }
threadtwo(){}
~threadtwo(){}
void run()
{
int i=10;
while(--i)
{
ur->mreturn(3,i);
}
}
};
class threadthree : public QThread
{
private:
user* ur;
public:
threadthree(user* u){ ur = u; }
threadthree(){}
~threadthree(){}
void run()
{
int i=10;
while(--i)
{
ur->mreturn(5,i);
}
}
};
#endif
主函数 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);
one.terminate();
one.wait();
two.terminate();
two.wait();
three.terminate();
three.wait();
return 0;
}
运行结果:
