qt 高并发编程及同步

高并发编程是指在同一时间处理多个任务的能力,通常用于提升应用程序的性能和响应速度。Qt提供了一系列强大的工具和类来实现高并发编程,包括多线程、异步编程和任务调度。

一、继承QThread

#include <QThread>

class Worker : public QThread {
    void run() override {
        for (int i = 0; i < 5; ++i) {
            qDebug() << "Worker thread running:" << i << " " << QThread::currentThreadId();
            QThread::sleep(1); // 模拟耗时操作
        }
    }
};



int main(int argc, char *argv[])
{

    QApplication a(argc, argv);

    Worker worker;
    worker.start();

    qDebug() << "main thread:" << QThread::currentThreadId();

    return a.exec();
}

二、使用moveToThread

class Worker : public QObject
{
    Q_OBJECT
public:
    ~Worker(){qDebug() << "~Worker";}

public slots:
    void doWork() {
        for (int i = 0; i < 5; ++i) {
            qDebug() << "Worker thread:" << QThread::currentThreadId() << "Iteration:" << i;
            QThread::sleep(1);
        }
        emit finished();
    }

signals:
    void finished();
};



int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QThread *thread = new QThread;
    Worker *worker = new Worker;

    worker->moveToThread(thread);

    QObject::connect(thread, &QThread::started, worker, &Worker::doWork);
    QObject::connect(worker, &Worker::finished, thread, &QThread::quit);
    QObject::connect(thread, &QThread::finished, worker, &Worker::deleteLater);
    QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater);

    thread->start();

    qDebug() << "main thread:" << QThread::currentThreadId();


    return a.exec();
}

三、使用QtConcurrent

#include <QtConcurrent>
#include <QFuture>

int doHeavyWork(int value)
{
    qDebug() << value << " thread:" << QThread::currentThreadId();
    QThread::sleep(1); // 模拟耗时操作
    return value * 2;
}


int main(int argc, char *argv[])
{

    QApplication a(argc, argv);

    qDebug() << "main thread:" << QThread::currentThreadId();

    QFuture<int> future = QtConcurrent::mapped(QList<int>{1, 2, 3, 4, 5}, doHeavyWork);
    future.waitForFinished(); // 等待所有任务完成

    qDebug() << future.results(); // 输出结果

    return a.exec();
}

四、使用QThreadPool和QRunnable

class MyRunnable : public QRunnable {
public:
    MyRunnable() {
        //setAutoDelete(true); // 任务完成后自动删除
    }
    ~MyRunnable()
    {
        qDebug() << "~MyRunnable";
    }

    void run() override {
        qDebug() << "Running in thread:" << QThread::currentThread();
        QThread::sleep(1); // 模拟耗时操作
    }
};


int main(int argc, char *argv[])
{

    QApplication a(argc, argv);

    qDebug() << "main thread:" << QThread::currentThreadId();

    QThreadPool *pool = QThreadPool::globalInstance(); // 获取全局线程池

    for (int i = 0; i < 3; ++i)
    {
        MyRunnable *runnable = new MyRunnable();
        pool->start(runnable); // 提交任务到线程池
    }

    return a.exec();
}

五、同步

1、QMutex同步

class Worker : public QThread {
public:
    Worker(QMutex *mutex, int &sharedCounter)
        : m_mutex(mutex), m_sharedCounter(sharedCounter) {}

    void run() override {
        for (int i = 0; i < 5; ++i) {
            // 使用 QMutexLocker
            QMutexLocker locker(m_mutex);
            // 访问共享资源
            m_sharedCounter++;
            qDebug() << "Thread:" << QThread::currentThread() << "Counter:" << m_sharedCounter;
            // 锁会在 locker 析构时自动释放
            QThread::sleep(1);
        }
    }

private:
    QMutex *m_mutex;
    int &m_sharedCounter;
};


int main(int argc, char *argv[])
{

    QApplication a(argc, argv);

    qDebug() << "main thread:" << QThread::currentThreadId();

    QMutex mutex; // 创建互斥量
    int sharedCounter = 0; // 共享资源

    Worker worker1(&mutex, sharedCounter);
    Worker worker2(&mutex, sharedCounter);

    worker1.start(); // 启动线程1
    worker2.start(); // 启动线程2

    worker1.wait(); // 等待线程1完成
    worker2.wait(); // 等待线程2完成

    return a.exec();
}

2、QSemaphore同步

class Worker : public QObject {
    Q_OBJECT

public:
    Worker(QSemaphore *semaphore) : semaphore(semaphore) {}

public slots:
    void doWork() {
        for (int i = 0; i < 10; ++i) {
            semaphore->acquire();
            qDebug() << "Worker thread:" << QThread::currentThreadId() << "Iteration:" << i;
            semaphore->release();
            QThread::sleep(1);
        }
    }

private:
    QSemaphore *semaphore;
};



int main(int argc, char *argv[])
{

    QApplication a(argc, argv);

    qDebug() << "main thread:" << QThread::currentThreadId();

    QSemaphore semaphore(1);
    QThread thread1, thread2;
    Worker worker1(&semaphore), worker2(&semaphore);

    worker1.moveToThread(&thread1);
    worker2.moveToThread(&thread2);

    QObject::connect(&thread1, &QThread::started, &worker1, &Worker::doWork);
    QObject::connect(&thread2, &QThread::started, &worker2, &Worker::doWork);

    thread1.start();
    thread2.start();


    return a.exec();
}

qq群交流:698593923

觉得有帮助的话,打赏一下呗。。

           

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值