Skip to content

Commit

Permalink
[core] Introduced the CSharedResource
Browse files Browse the repository at this point in the history
  • Loading branch information
maxsharabayko committed Apr 19, 2022
1 parent 1dacc2a commit f060f86
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
35 changes: 35 additions & 0 deletions srtcore/sync.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -353,3 +353,38 @@ int srt::sync::genRandomInt(int minVal, int maxVal)
#endif // HAVE_CXX11
}

////////////////////////////////////////////////////////////////////////////////
//
// CSharedResource class
//
////////////////////////////////////////////////////////////////////////////////

void srt::sync::CSharedResource::release()
{
ScopedLock lock(m_lock);
SRT_ASSERT(m_iResourceTaken > 0);
--m_iResourceTaken;
if (m_iResourceTaken == 0)
m_cond.notify_one();
}

void srt::sync::CSharedResource::acquire()
{
UniqueLock lock(m_lock);

// Allow reacquiring the resource from the same thread
if (m_iResourceTaken > 0 && this_thread::get_id() == m_thid)
{
++m_iResourceTaken;
return;
}

while (m_iResourceTaken > 0)
{
m_cond.wait(lock);
}

SRT_ASSERT(m_iResourceTaken == 0);
++m_iResourceTaken;
m_thid = this_thread::get_id();
}
50 changes: 50 additions & 0 deletions srtcore/sync.h
Original file line number Diff line number Diff line change
Expand Up @@ -871,6 +871,56 @@ CUDTException& GetThreadLocalError();
/// @param[in] minVal minimum allowed value of the resulting random number.
/// @param[in] maxVal maximum allowed value of the resulting random number.
int genRandomInt(int minVal, int maxVal);

////////////////////////////////////////////////////////////////////////////////
//
// CSharedResource class
//
////////////////////////////////////////////////////////////////////////////////

/// The class to synchronize acces to a shared resource.
/// Can be acquired multiple times by the same thread.
class CSharedResource
{
public:
CSharedResource()
: m_iResourceTaken(0)
{
}

/// Releases the shared resource. Can taken several times by the same thread,
/// therefore notifies another thread once finally release by this thread.
void release();

/// Acquires the shared resource. Can be acquired multiple times from the same thread,
/// would just increase the reference count. It the resource is taken, waits on a CV for a notification.
void acquire();

private:
Mutex m_lock;
Condition m_cond;
int m_iResourceTaken;
CThread::id m_thid;
};

/// Acquired the shared resource on creation, releases upon destruction.
class CScopedResourceLock
{
public:
CScopedResourceLock(CSharedResource& resource)
: m_rsrc(resource)
{
m_rsrc.acquire();
}

~CScopedResourceLock()
{
m_rsrc.release();
}

private:
CSharedResource& m_rsrc;
};

} // namespace sync
} // namespace srt
Expand Down

0 comments on commit f060f86

Please sign in to comment.