Qt5 QWaitCondition Example

I am introducing the QT5 concurrency library. I watched the QWaitCondition example ( http://qt-project.org/doc/qt-5.0/qtcore/qwaitcondition.html#details ).
Here, one stream (stream B) reads user input, and all other threads (stream A) process this input.

Theme A:

forever { mutex.lock(); keyPressed.wait(&mutex); ++count; mutex.unlock(); do_something(); mutex.lock(); --count; mutex.unlock(); } 

Theme B:

 forever { getchar(); mutex.lock(); // Sleep until there are no busy worker threads while (count > 0) { mutex.unlock(); sleep(1); mutex.lock(); } keyPressed.wakeAll(); mutex.unlock(); } 

The reason for using the count variable and extended mutex synchronization is to prevent character loss.
The problem is that I think there is still a chance that the character will be lost: imagine the following scenario:

  • Thread A processes the character and reduces countes (--count); mutex is freed; then Thread A stops

  • Thread B returns from sleep, acquires a mutex, sees that count == 0 and calls keyPressed.wakeAll (), and then unlocks the mutex. However, the call to wakeAll () goes nowhere, since thread A is not expecting.

  • Theme A starts again, opens the mutexes and goes into standby mode (). Since wakeAll () has already been called, the character is lost.

Am I right or am I missing something? If I'm right, how can I fix an example to really prevent it from missing characters?

+6
source share
1 answer

you're right

to fix this, the loop must be entered with the mutex already obtained:

 mutex.lock(); forever { keyPressed.wait(&mutex); ++count; mutex.unlock(); do_something(); mutex.lock(); --count; } mutex.unlock(); 
+10
source

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


All Articles