views:

48

answers:

1

Note: I am using the open source Poco C++ libraries

I have a parent thread that creates many child threads to deal with incoming connections, each of these child threads maintains an XML document, which the parent thread can request at anytime via callback. Therefore I have a mutex protecting this document.

My problem arises in that when I create an instance of my child thread (which is implemented as a class), I create the document and lock the mutex until the document is initialized (after starting the thread and getting some input from the user connection). When the initilization is complete, I unlock the mutex, and get an exception: Cannot unlock mutex. I realize now that this is because I technically locked it in the master thread.

What I am looking for ideas for is a threadsafe way to initialize my XMLDocument and have control of the mutex in the child thread.

A: 

I have a parent thread that creates many child threads to deal with incoming connections

Starting a thread per client is a bad idea. Check any thread pool implementation. Since you already have an object per thread, the conversion might be quite simple.

each of these child threads maintains an XML document, which the parent thread can request at anytime via callback. Therefore I have a mutex protecting this document. [...] I realize now that this is because I technically locked it in the master thread.

I presume that you lock mutex for child thread initialization? Then use semaphore instead of mutex.

Semaphore would be initialized in the main thread (where you do instantiate the child thread object) with value 0. When triggering the callback from the main thread you do decrement the semaphore before, increment after the call. In the child thread, increment the semaphore once the initialization of the XML is finished and main loop is started. When modifying the the XML, child thread would do the same decrement/increment.

If main thread would try to decrement the semaphore before child thread is initialized completely, it would block since the value of semaphore is still zero. After child thread finishes the initialization and make the initial increment, the semaphore would work as if it was a plain mutex. Because mutex (in its simplest form) is essentially a semaphore with max value of 1.

Dummy00001