Page 1 of 1

Deleting a wxMutex on detachable threads

Posted: Thu Apr 30, 2009 6:25 am
by Ugly!
Hi, I m having a problem.
I have some fire and forget threads that do some stuff. I m using two wxMutex declared as:

mainFrm.h

Code: Select all

class mainFrm:wxFrame{
...
public:
static wxMutex *s_mutexSerial; 
static wxMutex *s_mutexCfgNumber;
};
mainFrm.cpp

Code: Select all

wxMutex * mainFrm::s_mutexSerial = 0;
wxMutex * mainFrm::s_mutexCfgNumber = 0;
On frm init I assign new wxMutex to each pointer.

The problem is that the mutex are leaking when I close my app. But if I try to delete them they might be still in use by the detachables threads and I get a runtime error.

Any ideas? I think that I should wait for all secondary threads to finish before deleting the wxMutex's, but how can I do this if they are fire&forget threads (I don't keep any reference of them)?

Posted: Thu Apr 30, 2009 8:11 am
by Muetdhiver
Hello,

This may just deal with a way of thinking about threads.
You said you are trying to close your application while your threads are always running.

So in your thread execution, you must test them to know if they are requested to be deleted with TestDestroy() function.

Into your thread "Exit" function, you need to know which mutex is associated with your thread, and then just delete it into this Exit() function (remember that this function acts as an event called when the thread is really deleted).

But you can't close your application while your "detached" threads are always running.

If what I said before is not possible (TestDestroy() could not be called), please use "joinable" threads instead in order to interact with them in the parent class and delete them manually.

Good luck.

Re: Deleting a wxMutex on detachable threads

Posted: Thu Apr 30, 2009 1:31 pm
by catalin
Ugly! wrote:Any ideas? I think that I should wait for all secondary threads to finish before deleting the wxMutex's, but how can I do this if they are fire&forget threads (I don't keep any reference of them)?
Here's a very good way of doing what you need: link

If doublemax will join and say "hi" you should give the points to him ;)

Re: Deleting a wxMutex on detachable threads

Posted: Thu Apr 30, 2009 2:13 pm
by TrV
catalin wrote:
Ugly! wrote:Any ideas? I think that I should wait for all secondary threads to finish before deleting the wxMutex's, but how can I do this if they are fire&forget threads (I don't keep any reference of them)?
Here's a very good way of doing what you need: link
The problem is still the same because it's difficult to call any method (such as wxThread::Destroy()) of a fired thread if no reference is kept... IMHO which is a very bad idea : it wouldn't be very hard to keep a reference of the threads. And better than wxThread::Destroy(), a call to wxThread::Delete() terminate the thread gracefully.