【问题标题】:have QThread something like volatile member in Java? [duplicate]QThread 在 Java 中有类似 volatile 成员的东西吗? [复制]
【发布时间】:2013-05-02 20:00:44
【问题描述】:

我有 5 个 QThread 一起工作。 我有一个整数变量,我想在他们之间分享它! 一个线程对我的整数所做的工作对另一个线程很重要。 怎么能在他们之间分享?!

【问题讨论】:

    标签: multithreading qt


    【解决方案1】:

    在变量周围使用QMutexQMutexLocker

    编辑:

    QMutex * mutex = new QMutex();
    int shared_integer = 0;
    
    void func1()
    {
        int temp;    
        // lots of calculations
        temp = final_value_from_calculations;
    
        // about to save to the shared integer
        {
            QMutexLocker locker(mutex);// this thread waits until the mutex is unlocked.
            qDebug() << "Mutex is now locked!";
            // access the shared variable
            shared_integer = temp;
    
            // if you had some reason to return early here, the mutex locker would
            // unlock your putex for you properly!
            // return; // locker's destructor gets called and the mutex gets unlocked
    
        }// lockers's destructor gets called and the mutex gets unlocked
        qDebug() << "Mutex is now unlocked!";
    
    }
    
    void func2()
    {
        QMutexLocker locker(mutex);
        qDebug() << shared_integer;
    }
    

    【讨论】:

    • @HamedNorouzi 人们不会为你写这个,使用文档!
    猜你喜欢
    • 1970-01-01
    • 2015-11-26
    • 2015-12-14
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2015-11-03
    相关资源
    最近更新 更多