Qt同步不可能在这里?

Max*_*rch 2 c++ qt multithreading

考虑以下情况:

class SomeClass : public QObject
{
  Q_OBJECT
private:
    unsigned long long someVar;

public:
    unsigned long long getSomeVar(){
        return someVar;
    void threadFunc();
}
Run Code Online (Sandbox Code Playgroud)

threadFunc() 将在一个新线程中调用(你猜对了),它将如下所示:

void SomeClass::threadFunc()
{
  ++someVar;
  // Do stuff...
}
Run Code Online (Sandbox Code Playgroud)

现在,在另一个主题中,我想阅读someVar.我打电话来这样做getSomeVar().但是,需要同步.我怎么做?对于构成的线程somevar,同步并不难.它只会是

void SomeClass::threadFunc()
{
  mut.lock();
  ++someVar;
  mut.unlock();
  // Do stuff...
}
Run Code Online (Sandbox Code Playgroud)

QMutex mut在类声明中添加了一个.但是我该如何同步getSomeVar()?我不能只说:

unsigned long long getSomeVar(){
  mut.lock();
  return someVar;
  mut.unlock();
}
Run Code Online (Sandbox Code Playgroud)

mut.unlock()因为return之前的陈述而永远不会被召唤.

我知道通常这样的冲突可以通过写作来避免......

unsigned long long getSomeVar(){
  QMutex mut;
  // mut-constructor calls mut.lock()
  return someVar;
  // mut-destructor calls mut.unlock()
}
Run Code Online (Sandbox Code Playgroud)

...但在这种情况下,我需要的互斥体是相同的内径getSomeVar()threadFunc().我试过了

unsigned long long getSomeVar(){
  // constructing mutex from mut (which is the class' mutex)
  QMutex mutex(mut);
  // mutex-constructor calls mut.lock()
  return someVar;
  // mutex-destructor calls mut.unlock()
}
Run Code Online (Sandbox Code Playgroud)

但是互斥锁的拷贝构造函数是私有的.

我能在这做什么?

Chr*_*ris 7

您正在寻找QMutexLocker

{
    QMutexLocker locker(&mut);
    ...
}

// Goes out of scope, unlocks the mutex in its destructor
Run Code Online (Sandbox Code Playgroud)