Skip to content

Commit

Permalink
Refactor Lock: solve mutex in CLR problem.
Browse files Browse the repository at this point in the history
  • Loading branch information
Xottab-DUTY committed Jan 5, 2018
1 parent 15d57b5 commit 846fa30
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 25 deletions.
35 changes: 35 additions & 0 deletions src/xrCore/Threading/Lock.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
#include "stdafx.h"
#include "Lock.hpp"
#include <mutex>

struct LockImpl
{
std::recursive_mutex mutex;
};

Lock::~Lock()
{
delete impl;
}

#ifdef CONFIG_PROFILE_LOCKS
static add_profile_portion_callback add_profile_portion = 0;
Expand Down Expand Up @@ -28,6 +39,8 @@ struct profiler
}
};

Lock::Lock(const char* id) : impl(new LockImpl), lockCounter(0), id(id) {}

void Lock::Enter()
{
#if 0 // def DEBUG
Expand All @@ -39,8 +52,30 @@ void Lock::Enter()
mutex.lock();
isLocked = true;
}
#else
Lock::Lock() : impl(new LockImpl), lockCounter(0) {}

void Lock::Enter()
{
impl->mutex.lock();
lockCounter++;
}
#endif // CONFIG_PROFILE_LOCKS

bool Lock::TryEnter()
{
bool locked = impl->mutex.try_lock();
if (locked)
lockCounter++;
return locked;
}

void Lock::Leave()
{
impl->mutex.unlock();
lockCounter--;
}

#ifdef DEBUG
extern void OutputDebugStackTrace(const char* header);
#endif
36 changes: 11 additions & 25 deletions src/xrCore/Threading/Lock.hpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#pragma once
#include <mutex>
#include <atomic>

#include "Common/Noncopyable.hpp"

#ifdef CONFIG_PROFILE_LOCKS
typedef void (*add_profile_portion_callback)(LPCSTR id, const u64& time);
void XRCORE_API set_add_profile_portion(add_profile_portion_callback callback);
Expand All @@ -14,45 +15,30 @@ void XRCORE_API set_add_profile_portion(add_profile_portion_callback callback);
#define MUTEX_PROFILE_ID(a) STRINGIZER(CONCATENIZE(MUTEX_PROFILE_PREFIX_ID, a))
#endif // CONFIG_PROFILE_LOCKS

class XRCORE_API Lock
class XRCORE_API Lock : Noncopyable
{
struct LockImpl* impl;
public:
#ifdef CONFIG_PROFILE_LOCKS
Lock(const char* id) : lockCounter(0), id(id) {}
Lock(const char* id);
#else
Lock() : lockCounter(0) {}
Lock();
#endif

Lock(const Lock&) = delete;
Lock operator=(const Lock&) = delete;
~Lock();

#ifdef CONFIG_PROFILE_LOCKS
void Enter();
#else
void Enter()
{
mutex.lock();
lockCounter++;
}
void Enter();
#endif

bool TryEnter()
{
bool locked = mutex.try_lock();
if (locked)
lockCounter++;
return locked;
}
bool TryEnter();

void Leave()
{
mutex.unlock();
lockCounter--;
}
void Leave();

bool IsLocked() const { return !!lockCounter; }

private:
std::recursive_mutex mutex;
std::atomic_int lockCounter;
#ifdef CONFIG_PROFILE_LOCKS
const char* id;
Expand Down

0 comments on commit 846fa30

Please sign in to comment.