QMutex是否需要是静态的,因此该类实例的其他线程调用知道暂停其操作?

时间:2013-07-24 15:27:29

标签: c++ qt mutex qmutex

从多个线程调用以下append函数。我不希望数据重写一个追加,因为计数器还没有增加。

除了当前使用Append的线程之外,这会挂起所有线程吗?或者其他线程是否会继续运行而不附加数据?

互斥锁是否需要“STATIC”或者每个实例都知道暂停操作吗?

如果我不想打嗝,我假设我必须构建一个缓冲区来备份日志数据?

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();
}

5 个答案:

答案 0 :(得分:3)

不,它不需要static,只需将其设为classA中的成员,您也可以查看QMutexLocker以锁定范围并解锁互斥锁:

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

答案 1 :(得分:1)

QMutex不需要声明为静态,Qt将确保其他线程将等待直到互斥锁上发生解锁,然后才允许另一个线程继续在该函数中执行。

答案 2 :(得分:0)

为了解决我的问题,在多次运行之后,由于classA的多个实例化,我确实必须使互斥锁“静态”。使互斥锁成为一个成员是行不通的。

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();
}

答案 3 :(得分:0)

@jdl"将互斥锁作为成员不起作用"。 是的有效。尝试制作互斥"静态"像这样:

//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++;
}

答案 4 :(得分:-4)

由于我不知道QMutex是如何运作的,我只是做了自己的互斥锁。

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
    }

}