Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[core] Add a shared mutex class #2981

Merged
merged 11 commits into from
Aug 1, 2024
75 changes: 75 additions & 0 deletions srtcore/sync.h
Original file line number Diff line number Diff line change
Expand Up @@ -943,6 +943,81 @@ CUDTException& GetThreadLocalError();
/// @param[in] maxVal maximum allowed value of the resulting random number.
int genRandomInt(int minVal, int maxVal);

class SharedMutex
{
private:
maxsharabayko marked this conversation as resolved.
Show resolved Hide resolved
Condition m_LockWriteCond;
Condition m_LockReadCond;

Mutex m_Mutex;
int m_iCountRead;
bool m_bWriterLocked;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These two fields can be combined into one field. Please see /usr/include/c++/v1/shared_mutex.

Would be also nice that you use exactly the same public API as the standard one so that a prospective drop-in replacement with the standard one from C++17 can be done later.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about merging those two fields. I however felt that it would hurt readibility for a negligible memory and performance gain.

API has been changed to match the standard one



public:
SharedMutex()
:m_LockWriteCond()
,m_LockReadCond()
,m_Mutex()
,m_iCountRead(0)
,m_bWriterLocked(false)
{
m_iCountRead = 0;
m_bWriterLocked = false;

setupCond(m_LockReadCond, "SharedMutex::m_pLockReadCond");
setupCond(m_LockWriteCond, "SharedMutex::m_pLockWriteCond");
setupMutex(m_Mutex, "SharedMutex::m_pMutex");

}
~SharedMutex()
{
releaseMutex(m_Mutex);
releaseCond(m_LockWriteCond);
releaseCond(m_LockReadCond);
}

void lockWrite()
{
UniqueLock l1(m_Mutex);
if(m_bWriterLocked)
m_LockWriteCond.wait(l1);
m_bWriterLocked = true;
if(m_iCountRead)
m_LockReadCond.wait(l1);


}

void unlockWrite()
{
UniqueLock l2(m_Mutex);
m_bWriterLocked = false;
l2.unlock();
m_LockWriteCond.notify_all();

}

void lockRead()
{
UniqueLock l3(m_Mutex);
if(m_bWriterLocked)
m_LockWriteCond.wait(l3);
m_iCountRead++;
}

void unlockRead()
{
ScopedLock l4(m_Mutex);
m_iCountRead--;
if(m_bWriterLocked && m_iCountRead == 0)
m_LockReadCond.notify_one();
else if (m_iCountRead > 0)
m_LockWriteCond.notify_one();
}

};

} // namespace sync
} // namespace srt

Expand Down
Loading