使用多執行緒手動寫出迴圈列印ABABABAB...
阿新 • • 發佈:2019-02-15
平時沒在意,敲敲程式碼就出來了,可實際用筆在紙上書寫的時候就不知所措了
QT比較熟悉,就用它來實現吧!
#ifndef HELLOTHREAD_H #define HELLOTHREAD_H #include <QThread> #include <QMutex> class HelloThread : public QThread { public: HelloThread(int type=0); void stop(); protected: void run(); public: int m_type; int m_exitflag; private: static QMutex m_mutex; static int m_status; }; #endif // HELLOTHREAD_H
#include "hellothread.h" //靜態全域性變數 QMutex HelloThread::m_mutex; int HelloThread::m_status = 0; HelloThread::HelloThread(int type) : m_type(type) { m_exitflag = false; } void HelloThread::stop() { m_exitflag = true; } void HelloThread::run() { printf("\n enter thread = %p\n", QThread::currentThreadId() ); while( !m_exitflag ) { QMutexLocker locker(&HelloThread::m_mutex); if(0==this->m_type && HelloThread::m_status==0) { printf("A\n"); HelloThread::m_status = 1;//this->m_status也是可以的,但不規範 } else if(1==this->m_type && HelloThread::m_status==1) { printf("B\n"); HelloThread::m_status = 0;//this->m_status也是可以的,但不規範 } locker.unlock(); msleep(10); } m_exitflag = false; printf("\n leave thread = %p\n", QThread::currentThreadId() ); }
主要是用全域性變數實現執行緒間的通訊,為了保證全域性變數的狀態唯一,需要加鎖控制,就用最簡單的QMutex吧~~~~
#include <QCoreApplication> #include "hellothread.h" //實現多執行緒,迴圈列印ABABABABABAB...... int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); printf("in main thread...%p\n", QThread::currentThreadId() ); HelloThread TA(0); HelloThread TB(1); TA.start();//開啟執行緒 TB.start(); if( 'q'==getchar() )//等待使用者輸入 { TA.quit();//退出執行緒(不管用) TB.quit(); printf("in main exiting...\n"); TA.stop();//使用條件退出 TB.stop(); } TA.wait();//等待執行緒結束 TB.wait(); printf("in main exited thread...%p\n", QThread::currentThreadId()); exit(0);//按鍵才有效,為何? return a.exec(); }
貌似達到了目的,提筆就忘字,怎麼辦啊!!!