一緒に作業している 5 つの QThread があります。それらの間で共有したい整数変数が1つあります。あるスレッドが私の整数に対して行う作業は、別のスレッドにとって重要です。それらの間でどのように共有できますか?
1 に答える
0
QMutex
変数を a で囲んで使用し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;
}
于 2013-05-02T20:29:58.657 に答える