有QThread像Java中的volatile成员吗?

时间:2013-05-02 20:00:44

标签: multithreading qt

我有5个QThread正在协同工作。 我有一个整数变量,我希望在它们之间分享它! 一个线程对我的整数所做的工作对另一个线程很重要。 如何在它们之间分享?!

1 个答案:

答案 0 :(得分:0)

在变量周围使用QMutex QMutexLocker

编辑:

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;
}