问题:
程序有多少临界资源?需要多少线程锁?
一般性原则:
每一个临界资源都需要一个线程锁进行保护!
QMutex g_mutex_1;
QMutex g_mutex_2;
class ThreadA : public QThread
{
protected:
void run()
{
while( true )
{
g_mutex_1.lock();
qDebug() << objectName() << "get m1";
g_mutex_2.lock();
qDebug() << objectName() << "get m2";
qDebug() << objectName() << "do work ...";
g_mutex_2.unlock();
g_mutex_1.unlock();
sleep(1);
}
}
};
class ThreadB : public QThread
{
protected:
void run()
{
while( true )
{
g_mutex_1.lock();
qDebug() << objectName() << "get m2";
g_mutex_2.lock();
qDebug() << objectName() << "get m1";
qDebug() << objectName() << "do work ...";
g_mutex_2.unlock();
g_mutex_1.unlock();
sleep(1);
}
}
};
QSemaphore sem(1)
sem.acquire();
// do something
sem.release();
#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QMutex>
#include <QSemaphore>
#define SIZE 5
unsigned int g_store[SIZE] = {0};
QSemaphore g_sem_free(SIZE);
QSemaphore g_sem_used(0);
class Producer : public QThread
{
protected:
void run()
{
while(true)
{
int value = qrand() % 256;
g_sem_free.acquire();
for(int i=0; i<SIZE; i++)
{
if( !g_store[i])
{
g_store[i] = value;
qDebug() << objectName() << "generate : { " << i << ", " << value << "}";
break;
}
}
g_sem_used.release();
sleep(1);
}
}
};
class Consumer : public QThread
{
protected:
void run()
{
while(true)
{
g_sem_used.acquire();
for(int i=0; i<SIZE; i++)
{
if( g_store[i])
{
int value = g_store[i];
g_store[i] = 0;
qDebug() << objectName() << "Consumer : { " << i << ", " << value << "}";
break;
}
}
g_sem_free.release();
sleep(1);
}
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Producer p1;
Producer p2;
Producer p3;
p1.setObjectName("p1");
p2.setObjectName("p2");
p3.setObjectName("p3");
Consumer c1;
Consumer c2;
c1.setObjectName("c1");
c2.setObjectName("c2");
p1.start();
p2.start();
p3.start();
c1.start();
c2.start();
return a.exec();
}
注:本笔记根据狄泰软件学院课程做笔记!