There is such a code

for (;;) { //... _mutex.unlock(); f(); _mutex.lock(); //... } 

The f() function causes the Qt signal to be redrawn, the processing of which, as I understand it, occurs in a new thread unknown to me, and it does not always manage to capture the mutex and _mutex.lock from the code above works earlier. How can I make _mutex.lock run no earlier than the signal processing _mutex.lock ? I am using C ++ 11 threads.

  • one
    Without disclosure, "the signal processing will work out" is hardly possible to suggest something. What kind of treatment? Does it give a signal at the end of its work? And so, in general, any work on redrawing something in Qt is always performed in the main thread or otherwise, say the GUI stream. - alexis031182
  • Alternatively: select method (s). At the end of f() generate a signal like drawingFinished () and hang a slot with lock(); … lock(); … - LXA

1 answer 1

You are doing something wrong, blocking / unblocking a mutex should be the thread performing the work with the shared resource. That is, once the threads "know" about the resource, then they must "know" about the mutex. This means that you need to stretch the mutex inside f() . Or choose another synchronization scheme, for example, on messages, which, by the way, are Qt signals.

  • There was a reason why the window update had to be done via an update signal, and not directly, I don’t remember it, but I can search. Due to the fact that I do not call the update directly, the thread that is being created to update the window does not always have time to acquire the mutex earlier than _mutex.lock() from the code above. But this thread has access to this mutex and he loch it, but not always the first. After updating VS and Qt, it does not always have time to block it first, only in ~ 70% of cases. - Ufx
  • @Ufx Essentially you want them to work synchronously. Therefore, either do everything in one thread, or change the logic. The mere presence of mutex does not create parallelism, first of all, the logic itself must be such. - Cerbo
  • As far as I understand, calling the update signal calls the rendering function in some new stream. But if the rendering function itself is called in the same thread, for some reason, I don’t remember what reasons, it does not work, or it does not work as it should. That is, I have such a situation - I call a signal that creates a thread, and I need to wait for the completion of that new thread so that the code continues to run. - Ufx
  • @Ufx Write the question in more detail so that it is clear who is calling and who is waiting for what specifically does not work. - Cerbo
  • And what prevented the use of Qt-streams? In addition, QThread inherited from QObject and you can directly use the signal slots. - aleks.andr