首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

QT线程独占解决方案

2012-03-22 
QT线程独占各位大虾,我做了个线程独占的测试程序,代码如下:/******************定义两个线程thread1和thre

QT线程独占
各位大虾,我做了个线程独占的测试程序,代码如下:
/******************定义两个线程thread1和thread2**************************/
#ifndef   TEST_H
#define   TEST_H
#include   <qthread.h>
#include   <iostream.h>
#include   <qmutex.h>
#include   <qwaitcondition.h>
class   Thread1:public   QThread{
public:
              Thread1(QMutex   *mutex_1,   QWaitCondition   *cond_1){};
              ~Thread1(){};
            virtual   run(){
                              for(int   i=0;i <5;i++){
                                          cout < < "thread1   ping   " < <endl;
                                          sleep(1);
                              }  
            };          
};
class   Thread2:public   QThread{
public:
              Thread2(QMutex   *mutex_2,   QWaitCondition   *cond_2){};
              ~Thread2(){};
            virtual   run(){
                              for(int   i=0;i <5;i++){
                                          cout < < "------thread2   ping----   " < <endl;
                                          sleep(2);
                              }  
            };          
};
#endif
/*****************主程序如下********************/
#include   "test.h "
int   main(int   argc,   char   *argv[])
{
        QMutex   mutex;
        QWaitCondition   condition;
        Thread1   *thread1;
        Thtead2   *thread2;
        mutex.lock();
        thread1=new   Thread1(&mutex,   &condition);        
        thread1-> start();
        mutex.unlock();
        mutex.lock();
        thread2=new   Thread2(&mutex,&condition);        
        thread2-> start();
        mutex.unlock();
        return   0;
}
可是出现的是如下的结果;
thread1   ping
thread1   ping
------thread2   ping----
thread1   ping
thread1   ping
------thread2   ping----
thread1   ping
------thread2   ping----


------thread2   ping----
------thread2   ping----
不是我想要的结果,我想要的是:
thread1   ping
thread1   ping
thread1   ping
thread1   ping
thread1   ping
------thread2   ping----
------thread2   ping----
------thread2   ping----
------thread2   ping----
感觉好象是mutex.lock()根本就不起作用,没有锁住线程,我知道如果我用thread1-> wait()和thread2-> wait()可以得到我想要的结果,但是我想知道,mutex.lock()这个函数怎么用,因为我的程序里需要用到互斥线程去访问公共变量.那么,各位大虾,我怎么样使用mutex.lock()得到我想要的结果呢?



[解决办法]
对于这种多任务的操作系统,
我也想知道怎么让一个线程独占资源的?

[解决办法]
virtual run(){
//这里lock
for(int i=0;i <5;i++){
cout < < "thread1 ping " < <endl;
sleep(1);
}
//这里unlock
};

线程2和线程1加锁解锁的地方一样!!!

热点排行