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

你离开我真会死。 提交于 2019-12-03 17:23:26

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*/
}

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.

To solve my problem, after multiple runs, I did have to make mutex "Static" due to multiple instantiations of classA. Making mutex a member did not work.

void classA::Append(int _msg)
{
    static int c = 0;
    static QMutex mutex; //YES... 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();
}

@jdl "Making mutex a member did not work". Yes it works. Try to make mutex "Static" like this:

//classA.h
class ClassA {
    public:
        static QMutex mutex;
        // rest of variables and Methods
        // ...
}


//classA.cpp
QMutex ClassA::mutex; // Before all
ClassA::ClassA() {
    //Constructor
}
void ClassA::Append(int _msg) {
    static int c = 0
    QMutexLocker locker(&mutex)
    intArray[c] = _msg;
    c++;
}

Since I don't know how QMutex is really operating, I just did my own mutex.

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

    while(mutex == 1){
        //suspend thread
    }

    if(mutex == 0){
        mutex = 1;//lock        

        intArray[c] = _msg;
        c++;

        mutex = 0;//unlock
    }

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!