| 術語 | 定義 |
|---|---|
| 進程 | 資源分配最小單位,擁有獨立記憶體空間 |
| 線程 | CPU 調度最小單位,共享進程資源 |
| 並發 | 宏觀同時、微觀輪流(單核分時) |
| 並行 | 多核真正同時執行 |
| 同步 | 阻止有依賴關係的操作同時發生 |
| 異步 | 獨立操作互不阻塞、各自進行 |
class MyThread : public QThread {
Q_OBJECT
public:
MyThread() : stopped(false) {}
void stop() { stopped = true; }
protected:
void run() override {
int i = 0;
while (!stopped) {
qDebug() << "thread id:" << QThread::currentThreadId() << ":" << i++;
sleep(2);
}
stopped = false;
}
private:
volatile bool stopped;
};
關鍵點:start() 啟動線程並自動呼叫 run();isRunning() 判斷狀態;terminate() 強制結束(不推薦常用)。
控制有限資源存取,acquire() 取資源、release() 釋放。生產者-消費者經典範例:
QSemaphore freeBytes(100), usedBytes(0);
void Producer::run() {
for (int i=0; i<100; ++i) {
freeBytes.acquire(); // 等待空位
produce(i);
usedBytes.release(); // 通知有資料
}
}
void Consumer::run() {
for (int i=0; i<100; ++i) {
usedBytes.acquire(); // 等待資料
consume(i);
freeBytes.release(); // 歸還空位
}
}
等待特定條件成立,避免忙等待:
QMutex mutex;
QWaitCondition notFull, notEmpty;
int buffer[50], used = 0;
void Producer::run() {
for (int i=0; i<50; ++i) {
mutex.lock();
if (used == 50) notFull.wait(&mutex); // 釋放鎖並等待
buffer[used++] = i;
qDebug() << "produce" << i;
notEmpty.wakeAll(); // 喚醒消費者
mutex.unlock();
sleep(1);
}
}
void Consumer::run() {
for (int i=0; i<50; ++i) {
mutex.lock();
if (used == 0) notEmpty.wait(&mutex);
qDebug() << "consume" << buffer[--used];
notFull.wakeAll();
mutex.unlock();
sleep(2);
}
}
保護臨界區,lock()/unlock() 或配合 QMutexLocker 自動解鎖(RAII)。
thread->start(QThread::HighPriority); // 啟動時指定
thread->setPriority(QThread::LowPriority); // 運行中調整
優先級僅為調度提示,具體行為視作業系統而定。
exec()volatile bool stopped 只能防編譯器優化,**不能**保證多核可見性,正式專案請用 QAtomicInt 或 std::atomicsleep() 在 run() 中會阻塞事件迴路,需定時處理事件請用 QTimer 或 QEventLoopquit() + wait() 確保資源釋放掌握 Qt 多線程核心機制,善用訊號槽解耦、同步原語護航,即能編寫高效穩定的併發應用。