上代码:

#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();
}

测试结果 :

小结:

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

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

07-15 09:57