Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does QMutex need to be static so other threads calls of this class instance know to suspend their operations?

Tags:

c++

mutex

qt

qmutex

From multiple threads the following append function is called. I don't want data to re-write an append because the counter had not yet been incremented.

Will this suspend all threads coming in except for the one currently using Append? Or will the other threads just continue running and not append the data?

Does the mutex need to be "STATIC" or will each instance know to suspend operations?

If I don't want hiccups, I assume I have to build a buffer to back log data?

void classA::Append(int _msg)
{
    static int c = 0;
    QMutex mutex; //need to be static so other threads know to suspend?
                  //there are 10 threads creating an instantiation of classA or an object of classA     

    mutex.lock();

    intArray[c] = _msg;
    c++;

    mutex.unlock();
}
like image 753
jdl Avatar asked Nov 13 '22 01:11

jdl


2 Answers

No it doesn't need to be static, just make it a member in your classA and also you can take a look at QMutexLocker to scope lock and unlock the mutex:

void classA::Append(int _msg)
{
    static int c = 0;
    QMutexLocker locker(&mutex); // mutex is a QMutex member in your class

    intArray[c] = _msg;
    c++;

    /*mutex.unlock(); this unlock is not needed anymore, because QMutexLocker unlocks the mutex when the locker scope ends, this very useful especially if you have conditional and return statements in your function*/
}
like image 82
Zlatomir Avatar answered Nov 15 '22 04:11

Zlatomir


The QMutex does not need to be declared as static and Qt will ensure that other threads will wait until the unlock occurs on the mutex before allowing another thread to continue execution in that function.

like image 26
TheDarkKnight Avatar answered Nov 15 '22 04:11

TheDarkKnight