【发布时间】:2013-05-02 20:00:44
【问题描述】:
我有 5 个 QThread 一起工作。 我有一个整数变量,我想在他们之间分享它! 一个线程对我的整数所做的工作对另一个线程很重要。 怎么能在他们之间分享?!
【问题讨论】:
标签: multithreading qt
我有 5 个 QThread 一起工作。 我有一个整数变量,我想在他们之间分享它! 一个线程对我的整数所做的工作对另一个线程很重要。 怎么能在他们之间分享?!
【问题讨论】:
标签: multithreading qt
在变量周围使用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;
}
【讨论】: