#include <QtCore>
QMutex m1;
QMutex m2;
 
/*thread A : bloque m1 puis m2*/
class threadA : public QThread
{
 
protected :
    void run()
    {
        int nbTest (0);
        forever
        {
 
            m1.lock();
            if (m2.tryLock())
            {
                qDebug() << "/***Thread A bloque les deux mutex apres "<<nbTest<<" *******/" << endl;
                m2.unlock();
                nbTest = 0;
            }
            else
            {
                ++nbTest;
            }
 
            m1.unlock();
 
        }
    }
};
 
/*thread B : bloque m2 puis m1*/
class threadB : public QThread
{
 
protected :
    void run()
    {
        int nbTest (0);
        forever
        {
 
            m2.lock();
            if (m1.tryLock())
            {
                qDebug() << "\t/***Thread B  bloque les deux mutex aprs "<<nbTest<<" *******/" << endl;
                m1.unlock();
                nbTest = 0;
            }
            else
            {
                ++nbTest;
            }
 
            m2.unlock();
        }
    }
};
int main(int argc, char **argv)
{
    //creation et lancement des threads  
    threadA a; a.start();
    threadB b; b.start();
 
    //attente de la fin d'execution des deux threads
    a.wait(); b.wait();
}
 
live-lock.cpp.txt · Dernière modification: 2009/11/18 07:55 par mongaulois