QT下多线程独占一个变量
各位大虾,在我的工程中遇到一个让我很困惑的问题,我的工程需要从一个第三方函数库中读取一个函数,我用优先级不同的线程去读它的值,却发现并没有得到我预想的结果,我把代码贴出来,希望大虾们能够帮我解决这个问题,如下:
/*******第三方提供的头文件*******/
#ifndef APP_H
#define APP_H
typedef struct out{
int x;
int y;
}s; //结构体,x的值可以为1,y的值可以为2
int input(&s) //读入函数,返回1或者0,它从硬件实时读取值,当返回1时,表明结构体s从硬件上得到了数,此时s.x=1 , s.y=2当返回为0时,表明没有硬件的数据传上来;
#define APP_H
/******************定义两个线程thread1和thread2**************************/
,其中s是个结构体,原型为:
#ifndef TEST_H
#define TEST_H
#include <qthread.h>
#include <iostream.h>
#include <qmutex.h>
#include “app.h”
class Thread1:public QThread{
private:
QMtex mutex; //定义互斥锁
out s_1; //定义结构体,用于存放从硬件上读
取的数据
int i,y;
public:
Thread1();
~Thread1();
getdate(); //开启线程,获得硬件上的数据
virtual run(); //执行线程
};
class Thread2:public QThread{
private:
QMtex mutex; //定义互斥锁
out s_2; //定义结构体,用于存放从硬件上读
int j,y; 取的数据
public:
Thread2();
~Thread2();
getdate(); //开启线程,获得硬件上的数据
virtual run(); //执行线程
};
#endif
/*****************************线程函数****************************/
#include "test.h"
Thread1::Thread1(){}
Thread1::~Thread1(){
QThread::wait(); //等待线程结束
}
Thread1::getdate(){
QThread::start(QThread::LowPriority) //开启线程,定义优先级为低级
}
void Thread1::run(){
mutex.lock(); //锁住互斥量
while(1){ //线程一直开着,不能关
i=input(&s_1);//从硬件上读取数据
if(i==1 ){//当硬件有数据且满足条件时执行
cout<<"this is thread1 runing"<<endl;
x=s_1.x;
}
}
mutex.unlock(); //让出互斥量让其他线程运行
}
Thread2::Thread2(){}
Thread2::~Thread2(){
QThread::wait(); //等待线程结束
}
Thread2::getdate(){
QThread::start(QThread::HighPriority) //开启线程,定义优先级为高级
}
void Thread2::run(){
mutex.lock(); //锁住互斥量
while(1){ //这个线程可以关
cout<<"---------thread2 is start"<<endl;
j=input(&s_2);//从硬件上读取数据
if(i==1 ){//当硬件有数据且满足条件时执行
cout<<"this is thread2 runing"<<endl;
y=s_2.y;
break;
}
}
mutex.unlock(); //让出互斥量让其他线程运行
}
/*****************主程序如下********************/
#include "test.h"
int main(int argc, char *argv[])
{
QMutex mutex;
QWaitCondition condition;
Thread1 *thread1;
Thtead2 *thread2;
thread1=new Thread1();
thread1->getdate();
thread2=new Thread2();
thread2->getdate();
return 0;
}
输出结果如下:
---------thread1 is start
this is thread1 runing
this is thread1 runing
---------thread2 is start
this is thread1 runing
this is thread2 runing
this is thread2 runing
.
.
.
感觉优先级比较高的线程Thread2进去过,但是进去后j=input(&s_2)这条语句取不到,而让优先级比较低的Thread1的函数i=input(&s_1)取到了,然后满足Thread1的if(i==1 )条件,输出“this is thread1 runing”后,又转入Thread2的while(1)循环里面,不断输出“this is thread2 runing”
大虾们,我的问题是:为什么线程优先级高的Thread2类里面的不能读到第三方提供的函数j=input(&s_2),而总是被优先级低的Thread1占用呢?我哪里出错了?查看了很多资料,说是如果多线程访问公共变量需要加valotile修饰,但是我的是公共函数,我怎么加阿?有哪位高手可以指点迷津么?