Obtain a write lock on a resource. This will spin until either the lock is granted or the lock is deactivated (host entity destructed). And then spin until the read count falls to zero. This latter step ensures no thread can read the resource during a write.
| Return Type | Function name | Arguments |
|---|---|---|
| hzEcode | hzLockRW::LockWrite | (int32_t,) |
Declared in file: hzLock.h
Defined in file : hzLock.cpp
Function Logic:
Function body:
hzEcode hzLockRW::LockWrite (int32_t nTries)
{
// Obtain a write lock on a resource. This will spin until either the lock is granted or the lock is deactivated (host entity destructed). And
// then spin until the read count falls to zero. This latter step ensures no thread can read the resource during a write.
//
// Arguments: 1) nTries Number of retries (in thousands) before abandoning efforts to obtain the lock
//
// Returns: E_NOTFOUND The previous thread with write access killed the lock (should be because it deleted the applicable resource)
// E_TIMEOUT The thread holding write access has held the lock for too long
// E_OK Write access granted
_hzfunc("hzLockRW::LockWrite") ;
uint32_t cont ; // Contention or spin count
uint32_t tries ; // Contention or spin count
uint32_t tid ; // Thread id
uint32_t limit ; // Timeout as number of tries
if (!_hzGlobal_MT)
return E_OK ;
tid = pthread_self() ;
limit = nTries < 0? 0xfffffffe:nTries*1000;
if (m_lockval == tid)
Fatal("Attempt by thread %u to re-lock address %p\n", tid, &m_lockval) ;
// Wait for lock to become free (no other threads with write access)
for (tries = cont = 0;;)
{
if (m_lockval == 0xffffffff)
return E_NOTFOUND ;
if (m_lockval)
{ cont++ ; continue ; }
// Try to grab the lock
if (!__sync_val_compare_and_swap(&m_lockval, 0,tid))
{
if (m_lockval == tid)
break ;
}
// Check for timeout
tries++ ;
if (tries > limit)
return E_TIMEOUT ;
}
// Wait for counter to drop to zero
for (; m_counter ; cont++) ;
return E_OK ;
}