Should QMutex be static, so the other thread calls of this class instance know to pause their operations?

In several threads, the following add function is called. I do not want the data to overwrite the application, because the counter has not yet been increased.

Will all incoming streams be suspended except that the append is currently in use? Or will other threads continue to work and not add data?

Should the mutes be "STATIC" or does each instance know to pause operations?

If I don't need hiccups, I guess I need to create a buffer to track log data?

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
source share
5 answers

No, it doesn't have to be static , just make it a member in classA , and you can also take a look at QMutexLocker to lock the region and unlock the mutexes:

 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*/ } 
+3
source

QMutex does not have to be declared static, and Qt ensures that other threads will wait until unlocking occurs in the mutex before allowing another thread to continue executing in this function.

+1
source

To solve my problem, after several starts I had to make mutex "Static" due to multiple instances of class A. Executing the mutex function did not help.

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

@jdl "Make mutex a member didn't work." Yes it works. Try making mutex "Static" as follows:

 //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++; } 
0
source

Since I don’t know how QMutex works, I just made my own mutex.

 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 } } 
-3
source

Source: https://habr.com/ru/post/1493238/


All Articles