June 5, 2011

spsingh spsingh
Lab Rat
27 posts

How to know if a thread is waiting for a lock?

 

Consider the code below:

  1. void MyThread::run()
  2. {
  3.  sMutex.lock();
  4.  mHasLock = true;
  5.  SomeTask();
  6.  sMutex.unlock();
  7.  
  8.  emit done();
  9. }

sMutex is the static member of MyThread. Say, I have a 100 MyThreads, one of them is executing and the other 99 are waiting for a lock on this static mutex. At this instance the UI is closed, causing the destructor of MyThread to be called, I require that the thread that is executing wait() for completion and the other 99 are terminated safely. I have done it in the following way, But the documentation of terminate says that it is not safe to use it; is it safe in my scenario?

  1. MyThread::~MyThread()
  2. {
  3.  if (!mHasLock) {
  4.   // This thread is waiting for the lock, safe to terminate.
  5.   this->terminate();
  6.  }
  7.  if(this->isRunning()) {
  8.   this->quit();
  9.   this->wait();
  10.  }
  11. }

4 replies

June 5, 2011

romankr romankr
Lab Rat
16 posts

I’d recommend to do

  1. if (!mHasLock) {
  2.   return;
  3. }

June 5, 2011

goblincoding goblincoding
Ant Farmer
228 posts

Personally, doing it your way, I’d make mHasLock static also to ensure that only one thread can have mHasLock == true at any given point in time.

Alternatively, you can look at QMutex::trylock() for a different approach (checking whether a thread has or hasn’t got a lock).

To get back to your core issue, terminate() CAN be used, it just doesn’t have any built-in clean-up or safety checks, so the warning in the API docs is to ensure that YOU are sure :)

June 5, 2011

Denis Kormalev Denis Kormalev
Lab Rat
1654 posts

Not sure “static” advice is really good. In this case you will not know which thread is in lock (and in dtor you will terminate ALL threads). If you want to do it static for locking then mutex is already here.

June 26, 2011

goblincoding goblincoding
Ant Farmer
228 posts
Denis Kormalev wrote:
Not sure “static” advice is really good. In this case you will not know which thread is in lock (and in dtor you will terminate ALL threads). If you want to do it static for locking then mutex is already here.

Sorry, that was a very silly mistake to make on my part and what you say makes perfect sense, I just never considered it that way. Thanks for the input!

 
  ‹‹ How can i check if QMainWindow is fully loaded ?      [SOLVED] zoom to fit in QGraphicsView ››

You must log in to post a reply. Not a member yet? Register here!