c++ - Qt synchronization impossible here? -


consider following situation:

class someclass : public qobject {   q_object private:     unsigned long long somevar;  public:     unsigned long long getsomevar(){         return somevar;     void threadfunc(); } 

threadfunc() invoked in new thread (you guessed it), , this:

void someclass::threadfunc() {   ++somevar;   // stuff... } 

now, in thread, want read somevar. calling getsomevar(). however, synchronization needed. how do that? thread posesses somevar, synchronization not hard. it'll be

void someclass::threadfunc() {   mut.lock();   ++somevar;   mut.unlock();   // stuff... } 

with qmutex mut added in class declaration. how synchronize getsomevar() ? can't say:

unsigned long long getsomevar(){   mut.lock();   return somevar;   mut.unlock(); } 

mut.unlock() never called because of return-statement before.

i know such conflicts avoided writing...

unsigned long long getsomevar(){   qmutex mut;   // mut-constructor calls mut.lock()   return somevar;   // mut-destructor calls mut.unlock() } 

... in case, need mutex same inside getsomevar() , threadfunc(). tried

unsigned long long getsomevar(){   // constructing mutex mut (which class' mutex)   qmutex mutex(mut);   // mutex-constructor calls mut.lock()   return somevar;   // mutex-destructor calls mut.unlock() } 

but copy-constructor of mutex private.

what can here?

you're looking qmutexlocker

{     qmutexlocker locker(&mut);     ... }  // goes out of scope, unlocks mutex in destructor 

Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -