1.概要
qt 设置线程锁
2.内容
在 Qt 中,你可以使用 QMutex
、QReadWriteLock
或 QSemaphore
来实现线程锁。这些类提供了线程同步机制,确保多个线程在访问共享资源时不会发生竞争条件(race conditions)。以下是一些常见用法示例:
使用 QMutex
QMutex
是一个轻量级的互斥锁,用于保护共享资源或代码段,使其在任何时候只能由一个线程访问。
#include <QMutex>
#include <QThread>
#include <QDebug>
QMutex mutex;
class MyThread : public QThread
{
Q_OBJECT
public:
void run() override {
mutex.lock();
qDebug() << "Thread" << QThread::currentThreadId() << "is running";
// 访问共享资源的代码
mutex.unlock();
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyThread thread1, thread2;
thread1.start();
thread2.start();
thread1.wait();
thread2.wait();
return a.exec();
}
#include "main.moc"
使用 QReadWriteLock
QReadWriteLock
允许多个线程同时读取,但只允许一个线程写入。这对于读多写少的场景特别有用。
#include <QReadWriteLock>
#include <QThread>
#include <QDebug>
QReadWriteLock readWriteLock;
class ReadThread : public QThread
{
Q_OBJECT
public:
void run() override {
readWriteLock.readLock();
qDebug() << "Read Thread" << QThread::currentThreadId() << "is running";
// 读取共享资源的代码
readWriteLock.unlock();
}
};
class WriteThread : public QThread
{
Q_OBJECT
public:
void run() override {
readWriteLock.writeLock();
qDebug() << "Write Thread" << QThread::currentThreadId() << "is running";
// 写入共享资源的代码
readWriteLock.unlock();
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ReadThread readThread1, readThread2;
WriteThread writeThread;
readThread1.start();
readThread2.start();
writeThread.start();
readThread1.wait();
readThread2.wait();
writeThread.wait();
return a.exec();
}
#include "main.moc"
使用 QSemaphore
QSemaphore
是信号量,用于控制对资源的访问,通常用于限制一组资源的并发访问数量。
#include <QSemaphore>
#include <QThread>
#include <QDebug>
QSemaphore semaphore(3); // 允许最多3个线程同时访问
class MyThread : public QThread
{
Q_OBJECT
public:
void run() override {
semaphore.acquire();
qDebug() << "Thread" << QThread::currentThreadId() << "is running";
// 访问共享资源的代码
semaphore.release();
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyThread thread1, thread2, thread3, thread4;
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread1.wait();
thread2.wait();
thread3.wait();
thread4.wait();
return a.exec();
}
#include "main.moc"
以上是 Qt 中常用的几种线程同步机制的基本用法。根据实际需求选择合适的锁机制,以确保多线程程序的安全性和正确性。