一个进程可以分成多个线程,每个线程有自己的Register Set(寄存器组)和Stack,但共享进程的Heap、Data、Code (见下图)
创建线程:
//Producer.h
- #ifndef
PRODUCER_H - #define
PRODUCER_H - #include
<QThread> - #include
<QString> - class
Producer public: QThread - {
- public:
-
Producer( QString &prefix); -
stopThread( boolisStop); - protected:
-
produceMessage( intx); -
run(); - private:
-
QString m_prefix ; -
stopThreads ; - };
- #endif
// PRODUCER_H - //Producer.cpp
- #include
<QDebug> - #include
"Producer.h" - Producer::Producer(const
QString &prefix) : QThread() - {
-
m_prefix = prefix; -
stopThreads = - }
- void
Producer::stopThread( boolisStop) { -
stopThreads = isStop; - }
- void
Producer::produceMessage( intx) - {
-
qDebug() << QString( %1: ).arg(m_prefix).arg(x);%2" - }
- void
Producer::run() { -
i = 0; !stopThreads; i++) { -
produceMessage(i); -
msleep(rand()000+1); -
} - }
- //main.cpp
- #include
<QApplication> - #include
<QMessageBox> - #include
<QDebug> - #include
"Producer.h" - bool
stopThreads false;= - int
main( intargc, char*argv[]) - {
-
QApplication a(argc, argv); -
Producer pa( //创建线程对象 -
Producer pb( -
pa.start(); 启动线程 -
pb.start(); -
QMessageBox::information( 0, "Close me to stop!" ); -
pa.stopThread( -
pb.stopThread( -
pa.wait(); -
pb.wait(); -
0; - }
线程同步:
- QMutex
- QMutexLocker
- QReadWriteLock
- QReadLocker / QWriteLocker
- QSemaphore
//QMutex: 保护lock()与unlock()之间的代码
- QMutex
mutex; - mutex.lock();
- //需要保护的代码或数据存取
- mutex.unlock();
- //QLocker:
保护从QLocker对象创建后的整个函数体内的代码,函数结束后该locker会自动释放“锁”
- void
fun() { -
QMutexLocker locker(&mutex); -
other code - }
- //QReadWriteLock与QMutex比较相似,不过它提供的函数是:lockForRead()、lockForWrite()
- //同样,QReadLocker、QWriteLocker与QLocker的使用相似,能够自动释放“锁”
- //QSemaphore:
上面几种“锁”只能保护一个数据,如果有多个数据要保护,则需要使用QSemaphore
- QSemaphore
s( 10 ); - s.acquire();
s.available() = 9 - s.acquire(5);
s.available() = 4 - s.release(2);
s.available() = 6 - s.release();
s.available() = 7 - s.release(5);
s.available() = 12 - s.tryAcquire(15);
// s.available() = 12
从上面可以看出:以“Locker”结尾的“锁”用起来更加方便,因为它的对象在销毁时会自动释放锁;而不带"Locker"锁在使用时要注意处理如异常、条件判断等以保证锁能够被释放,否则可能会造成线程“锁”不释放,而被“锁”住的资源/代码不能够被别的线程访问。