测试QT读写锁(QReadWriteLock)和互斥锁(QMutex)的执行效率

文章通过一系列测试展示了在多线程场景下,使用QReadWriteLock(读写锁)和QMutex(互斥锁)进行读写操作的效率。测试表明,当指定线程写、多个线程读时,读写锁的效率高于多个线程同时读写的效率,但整体上,互斥锁的执行速度更快。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上代码:

#include <QCoreApplication>
#include <QElapsedTimer>
#include <QtConcurrent>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qSetMessagePattern("(%{time hh:mm:ss.zzz} %{threadid} %{file}:%{line}): \t%{message}");

    QList<int> list_report;

    for (int round = 0; round < 5; round++)
    {
        QMutex *mtx_lock = new QMutex;
        QReadWriteLock *rw_lock = new QReadWriteLock;
        QFutureWatcher<void> *watcher = new QFutureWatcher<void>;
        QSemaphore semaphore;

        QAtomicInt times = 1000 * 1000; //1m
        QDateTime datatime;

        QElapsedTimer timer;
        timer.start();

        for (int i = 0; i < 5; i++)
        {
            QFuture<void> future = QtConcurrent::run([&, i]() {
                int index = i;
                int write_times{0};

                semaphore.release(1);

                while (times > 0) {
                    int type = QRandomGenerator::global()->bounded(2);
                    if (type == 1 and index == 0) {
//                        QWriteLocker locker(rw_lock);
//                        datatime = QDateTime::currentDateTime();

                        QMutexLocker locker(mtx_lock);
                        datatime = QDateTime::currentDateTime();

                        write_times++;

                    } else {
//                        QReadLocker locker(rw_lock);
//                        auto newdata = datatime;

                        QMutexLocker locker(mtx_lock);
                        auto newdata = datatime;


                    }
                    times--;
                }

                qDebug()<<index<<"write:times"<<write_times;
            });

            watcher->setFuture(future);
        }

        semaphore.acquire(1);
        watcher->waitForFinished();
        qDebug() << round << "QFuture (ms)" << timer.elapsed()<<"------------------------------------";

        list_report.append(timer.elapsed());

        delete (watcher);
        delete (rw_lock);
        delete (mtx_lock);
    }

    qDebug()<<"report:"<<list_report;


    return a.exec();
}

测试结果 :

5线程 (1000  * 1000)
写概率指定线程写结果(单位:ms)平均写入次数
读写锁1/1000(193, 191, 183, 188, 186)200
互斥锁1/1000(111, 112, 109, 105, 106)200
互斥锁1/2(2808, 2790, 2722, 2719, 2800)100000
互斥锁1/5(1160, 1133, 1142, 1163, 1137)40000
读写锁1/5(4627, 4689, 4614, 4524, 4617)40000
互斥锁1/2(321, 303, 399, 358, 338)50000
读写锁1/2(1406, 1387, 1412, 1388, 1412)50000

小结:

读写锁QReadWriteLock 在指定线程写多个线程读,效率明显比多个线程同时读写好。

但是,都远低于互斥锁QMutex的执行效率。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值