Skip to content

Commit

Permalink
Implement spin lock using std::atomic
Browse files Browse the repository at this point in the history
  • Loading branch information
vigsterkr committed Jan 25, 2017
1 parent 0f5a975 commit 91c79df
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/shogun/lib/Lock.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@
#define PTHREAD_LOCK_DESTROY(lock) pthread_spin_destroy(lock)
#define PTHREAD_LOCK(lock) pthread_spin_lock(lock)
#define PTHREAD_UNLOCK(lock) pthread_spin_unlock(lock)
#endif
#endif // DARWIN
#else
#define PTHREAD_LOCK_T pthread_mutex_t
#define PTHREAD_LOCK_INIT(lock) pthread_mutex_init(lock, NULL)
#define PTHREAD_LOCK_DESTROY(lock) pthread_mutex_destroy(lock)
#define PTHREAD_LOCK(lock) pthread_mutex_lock(lock)
#define PTHREAD_UNLOCK(lock) pthread_mutex_unlock(lock)
#endif
#endif
#endif // USE_SPINLOCKS
#endif // HAVE_PTHREAD

using namespace shogun;

Expand All @@ -56,14 +56,22 @@ CLock::~CLock()

void CLock::lock()
{
#ifdef HAVE_PTHREAD
#ifdef HAVE_CXX11_ATOMIC
while(m_flag.test_and_set(std::memory_order_acquire));
#elif HAVE_PTHREAD
PTHREAD_LOCK((PTHREAD_LOCK_T*) lock_object);
#else
SG_NOTIMPLEMENTED
#endif
}

void CLock::unlock()
{
#ifdef HAVE_PTHREAD
#ifdef HAVE_CXX11_ATOMIC
m_flag.clear(std::memory_order_release);
#elif HAVE_PTHREAD
PTHREAD_UNLOCK((PTHREAD_LOCK_T*) lock_object);
#else
SG_NOTIMPLEMENTED
#endif
}
8 changes: 8 additions & 0 deletions src/shogun/lib/Lock.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@

#include <shogun/lib/config.h>

#ifdef HAVE_CXX11_ATOMIC
#include <atomic>
#endif

namespace shogun
{
/** @brief Class Lock used for synchronization in concurrent programs. */
Expand All @@ -29,7 +33,11 @@ class CLock

private:
/** lock object */
#ifdef HAVE_CXX11_ATOMIC
std::atomic_flag m_flag = ATOMIC_FLAG_INIT;
#else
void* lock_object;
#endif
};
}
#endif // __LOCK_H__

0 comments on commit 91c79df

Please sign in to comment.