Hangs at WaitForSingleObject()
-
Monday, December 11, 2006 8:02 AMHi all,
in my code i have sth like this:
try{ ......
CriticalSection.Lock();
......
CriticalSection.Unlock();
CriticalSection.Lock();
}catch(exception){
do something here
}
At the very first CriticalSection.lock(), it will go into the lock() function shown below and seems to hang at the statement in red color. I have placed debug points after the red line but did not seem to even go to 'return false".
Nothing got to do with my try and catch statement right? I am working in VS 2005. Previously without the try and catch statement, program was working fine.
inline bool Lock(const DWORD& dwMilliseconds = INFINITE){
if (::InterlockedCompareExchange(&m_lLockCount, 1, 0) == 0){
m_dwThreadID = ::GetCurrentThreadId();
return true;
}
if (m_dwThreadID == ::GetCurrentThreadId()){
++m_lLockCount;
return true;
}
if (::WaitForSingleObject(m_hEventUnlocked, dwMilliseconds) == WAIT_OBJECT_0)
return Lock(dwMilliseconds);
return false;
}
Please give some suggestions, thx.
Atiz
All Replies
-
Monday, December 11, 2006 8:28 AMModerator
"Nothing got to do with my try and catch statement right?"
Well, you can remove the try/catch and see if it works or not.
However I'm concerned with the corectness of this Lock function. InterlockedCompareExchange returns the original value of m_lLockCount so if m_lLockCount is 0 and 2 threads execute the if at the same time the if statement will be entered and m_dwThreadID will be assigned by both of the threads resulting in both threads being in the CriticalSection at the same time.
-
Monday, December 11, 2006 8:29 AM
Can you confirm that m_lLockCount is initialized to zero when the program starts and the m_hEventUnlocked event is correctly signaled in your Unlock function? Is the second Lock before catch necessary? Why do not use critical sections or mutexes provided by Windows?
-
Monday, December 11, 2006 8:38 AM
Mike Danes wrote: [...] InterlockedCompareExchange returns the original value of m_lLockCount so if m_lLockCount is 0 and 2 threads execute the if at the same time the if statement will be entered [...]
(I think only one thread will receive 0 from atomic InterlockedCompareExchange. The other thread will receive 1 exchanged by the first thread).
-
Monday, December 11, 2006 8:40 AMModeratorRight, it's reading the original value inside the "interlocked" section... I need to get my cofee... :)
-
Monday, December 11, 2006 9:01 AM
>Can you confirm that m_lLockCount is initialized to zero when the program starts
Hi peeps, I checked on the value of m_lLockCount and realised at that moment, it was returning me a 1 -_-
Upon further debugging,
I realised that another thread has locked on the data so it couldn't move on and stuck there. :p
(think cos I made mass changes to the code so some careless mistakes there, I need coffee too lol)
I really appreciate all of your help, thanks alot!
Atiz

