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

标签 c++ qt mutex qmutex

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

这会暂停所有进入的线程,除了当前使用 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();
}

最佳答案

不,它不需要是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*/
}

关于c++ - QMutex 是否需要是静态的,以便此类实例的其他线程调用知道暂停它们的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17838449/

相关文章:

Java 非重入锁实现

c++ - 二进制 '=' : no operator found which takes a left-hand operand of type 'const Thing'

c++ - 应用程序在 Eclipse 中编译,但在 Qt 中出现 'undefined reference errors'

c++ - 霍尔分区代码不起作用

qt - 设置 Loader 项目属性

c++ - 停留在窗口顶部的非模态 QWidget 对话框

c++ - 互斥体更改是否会广播到多核系统上的其他内核?

python - 这是在两个线程之间使用变量的正确方法吗?

c++ - C++ 中的 10 或 12 位字段数据类型

c++ - CMyPrintDialog::OnInitDialog() 未在 IE10 中调用