QMutex 是否需要是静态的,以便此类实例的其他线程调用知道挂起它们的操作?

jdl*_*jdl 5 c++ qt mutex qmutex

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

除了当前使用 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();
}
Run Code Online (Sandbox Code Playgroud)

Zla*_*mir 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*/
}
Run Code Online (Sandbox Code Playgroud)