5

从多个线程调用以下附加函数。我不希望数据重写追加,因为计数器尚未增加。

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

互斥体是否需要“静态”或每个实例都知道暂停操作?

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

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

5 回答 5

4

不,它不需要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*/
}
于 2013-07-24T15:40:42.453 回答
1

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

于 2013-07-24T15:41:52.087 回答
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();
}
于 2013-07-24T17:56:03.340 回答
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++;
}
于 2015-08-21T14:25:53.703 回答
-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
    }

}
于 2013-07-24T18:11:21.927 回答