05-10-2009 10:13 AM
Dear threading experts,
is there any side effect if I use the macros 'GetPointerTo' and 'ReleasePointerTo' inside a thread lock, that is in code located in between CmtGetLock and CmtReleaseLock?
Phrased differently, what kind of sequence is preferred if I need to modify a TSV within a piece of code that should be accessed only from one thread at a time:
1)
CmtGetLock
...
CmtReleaseLock
GetPointerTo
...
ReleasePointerTo
CmtGetLock
...
CmtReleaseLock
OR
2)
CmtGetLock
...
GetPointerTo
...
ReleasePointerTo
...
CmtReleaseLock
Thank you!
Wolfgang
Solved! Go to Solution.
05-10-2009 07:51 PM
Hi Wolfgang.
GetPointerTo.. will block until the thread holding the pointer releases it, so the CmtGetLock() and CmtReleaseLock() calls are unnecessary, unless they are protecting some other variable(s), in which case sequence 2) is the way to go.
Remember that if you are using multiple thread safe variables or multiple thread locks, and you need to use more than one at any time, each thread must get and release the pointers / locks in the same order. This avoids the possibility of deadlock. Also, each thread must release the resource as quickly as possible.
Example (using thread locks):
if(!CmtGetLock(lock1))
{
if(!CmtGetLock(lock2)) // Get lock2 only when holding lock1
{
...
CmtReleaseLock(lock2); // Always release lock2 before lock1
}
CmtReleaseLock(lock1);
}
Regards,
Colin.
05-11-2009 01:52 AM
Thanks, Colin, for pointing out version (2). Indeed I have some code with local variables that should be accessed only from one thread at a time, hence I need the CmtGetLock.
Wolfgang