Click to See Complete Forum and Search --> : CMutex lock problem


mwong7025
December 16th, 2004, 07:35 PM
I have a ClistCtrl derived class, and only a single instance of this class will be used in the program. To make it thread safe, I use a CMutex object for updating the list since the list can be updated from several threads. Sometimes the locking does not work the program will be hung when calling the lock with CSingleLock. The ListCtrlMutex is declared as global in the application. I am wondering if this causes the problem. I am thinking of moving the ListCtrlMutex inside the CmyListCtrl class as a static variable. Would this solve the problem and why?

Thank in advance for any help.

class CMyListCtrl: public CListCtrl
{
// Construction
public:
CMyListCtrl();
}

bool CMyListCtrl::UpdateList()
{
CSingleLock csl(&ListCtrlMutex);
csl.Lock();

...
}

gstercken
December 16th, 2004, 07:56 PM
A few things: Using a mutex for that is overkill, IMO - since you only want to synchronize the access to your list among threads (not processes), a critical section would be fine (and much more efficient).

Sometimes the locking does not work the program will be hung when calling the lock with CSingleLock.What do you mean by "it does not work"? Is the lists consistency corrupted by the fact that multiple threads update it concurrently, or are you experiencing a deadlock? Remember, when protecting an object with a critical section (or a mutex, for that matter), every single place which accesses the object must call lock/unlock, or the protection is useless.

The ListCtrlMutex is declared as global in the application. I am wondering if this causes the problem.Most probably not (since you o nly have one instance of the list control) - but the design is questionable, since it effectively prevents you from having multiple instances.

I am thinking of moving the ListCtrlMutex inside the CmyListCtrl class as a static variable.Yes, you should absolutely make the critical section a member of the list control class - but why static? After all, you want to protect a single instance of your control against concurrent accesses, and not all controls of the same class.

mwong7025
December 16th, 2004, 08:14 PM
If CMutex a overkill, what should I be using?

When I said it doesn't work, I mean sometimes (not all the time) it hangs in the Lock function.

gstercken
December 16th, 2004, 08:25 PM
If CMutex a overkill, what should I be using?As I said - a critical section.

Andreas Masur
December 17th, 2004, 03:40 AM
[ Moved thread ]

mwong7025
December 17th, 2004, 11:26 AM
What do you mean by moved thread?

gstercken
December 17th, 2004, 11:55 AM
What do you mean by moved thread?That means that the thread has been moved to a more appropriate forum: "Multihreading".