-3

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

4

1 回答 1

0

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;
}
于 2013-05-02T20:29:58.657 回答