November 2, 2010

phamtv phamtv
Lab Rat
135 posts

threading…

 

I have a multi-threaded application with an object that has re-entrant functions. I am trying to make my object thread safe by including a mutex. I am wondering if you can do multiple QMutexLocker locker on one instance of mutex within the same thread. For instance:

  1. class Sample : Public QThread
  2. {
  3. protected:
  4. void run();
  5.  
  6. public:
  7.  Sample();
  8. ~ Sample();
  9.  
  10. private:
  11. mutable QMutex mutex;
  12. bool Connect()
  13. {
  14.     QMutexLocker locker(&mutex);
  15.  
  16.     Disconnect();
  17. };
  18. bool Disconnect()
  19. {
  20.     QMutexLocker locker(&mutex);
  21.  
  22.     obj.close();
  23. };
  24. bool ReadRegister();
  25. bool WriteRegister();
  26. }

notice in my connect function I am calling my Disconnect function that also tries to do a QMutexLocker on global variable mutex.

- Tien

4 replies

November 2, 2010

tbscope tbscope
Lab Rat
26 posts

I am wondering if you can do multiple QMutexLocker locker on one instance of mutex within the same thread.

Yes. When the mutex is locked, all other functions that require it to be unlocked, will wait (block) till the mutex is unlocked.

Edit: But in your case, you will halt the thread forever. You can not call a function that requires the mutex to be unlocked from within a function that actually locks the mutex unless you unlock the mutex first. But in your case, the mutex is unlocked when the connect() function goes out of scope (the mutex locker is destroyed)

 Signature 

 

November 2, 2010

phamtv phamtv
Lab Rat
135 posts

is it true i can set the recursive mode for the mutex to recursive for me to continue my process? How can I set the recursive mode? I tried the following but get an error:

  1. class test : Public QThread
  2. {
  3. protected:
  4. void run();
  5.  
  6. private:
  7. QMutex mutex;
  8. public :
  9. test()
  10. {
  11. mutex = new QMutex(QMuted::Recursive);  // i canĀ“t construct mutex object...
  12. };
  13. ~test();
  14.  
  15. }

November 2, 2010

phamtv phamtv
Lab Rat
135 posts

i got it to work…. QMutex has to be declare as a QMutex pointer for me to do a new….

November 2, 2010

tbscope tbscope
Lab Rat
26 posts

QMuted should be QMutex?

 Signature 

 

 
  ‹‹ does try finally statement work???      which different between private QMutex in QThread and global one? ››

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