Trying to understand CSingleLock behavior
-
terça-feira, 3 de abril de 2012 10:23
I have inherited some code that looks like the methods below. I am trying to understand why the code
doesn't block when getSomeValueforDisplay() is called? I understand that local_lock is local, but I don't understand
the interaction with m_mutex.
Thanks.
CMutex m_mutex; float m_fSomeValue; int myclass::getSomeValue() { CSingleLock local_lock(&m_mutex, TRUE); int iSomeValue = (int) (m_fSomeValue * 10.0); return iSomeValue; } short myclass::getSomeValueforDisplay() { CSingleLock local_lock(&m_mutex, TRUE); short sSomeValue = (short) getSomeValue(); return sSomeValue; }
rhfritz
Todas as Respostas
-
terça-feira, 3 de abril de 2012 17:25Proprietário
Hello,
Do you mean, why doesnt it block because the same mutex is being acquired twice?
I believe CMutex is backed by windows mutex, which is reentrant i.e. the same thread can lock it many times without blocking.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684266(v=vs.85).aspx
"After a thread obtains ownership of a mutex, it can specify the same mutex in repeated calls to the wait-functions without blocking its execution."
Rahul V. Patil
- Sugerido como Resposta Rahul V. PatilModerator terça-feira, 3 de abril de 2012 17:25
- Marcado como Resposta rhfritz terça-feira, 3 de abril de 2012 23:53
-
terça-feira, 3 de abril de 2012 23:51
Thank you, Mr. Patil. That does make sense: Only another thread would be blocked. Is there any performance penalty for attempting to lock it again?
And just for clarification because the CSingleLock MSDN example doesn't handle this simple case, but in the following case there's no need to test the lock:
CSingleLock local_lock(&m_mutex, TRUE); if (local_lock.IsLocked()) ... // This line is redundant
because the default timeout is INFINITE therefore any line of code after the declaration could only be reached if the lock was successful. Is this a correct interpretation?
Thanks.
rhfritz
- Editado rhfritz terça-feira, 3 de abril de 2012 23:52
-
quarta-feira, 4 de abril de 2012 18:54Proprietário
Re:Performance
There will be an additional look up internally. But it shouldnt be something most developers worry about.
Re: redundant line.
My interpretation is the same as yours - given that the default waits infinitely until the lock acquires.
Thanks!
Rahul V. Patil
- Marcado como Resposta rhfritz quinta-feira, 5 de abril de 2012 00:04

