diff --git a/base_c/include/embb/base/c/mutex.h b/base_c/include/embb/base/c/mutex.h index fdaabb5..dd15c89 100644 --- a/base_c/include/embb/base/c/mutex.h +++ b/base_c/include/embb/base/c/mutex.h @@ -179,6 +179,9 @@ int embb_spin_init( /** * Spins until the spinlock can be locked and locks it. * + * \note This method yields the current thread in regular, + * implementation-defined intervals. + * * \pre \c spinlock is initialized \n * \post If successful, \c spinlock is locked. * \return EMBB_SUCCESS if spinlock could be locked. \n diff --git a/base_c/src/mutex.c b/base_c/src/mutex.c index 7e29b43..601e16b 100644 --- a/base_c/src/mutex.c +++ b/base_c/src/mutex.c @@ -25,6 +25,7 @@ */ #include +#include #include #include @@ -125,10 +126,15 @@ int embb_spin_init(embb_spinlock_t* spinlock) { int embb_spin_lock(embb_spinlock_t* spinlock) { int expected = 0; + int spins = 1; // try to swap the while (0 == embb_atomic_compare_and_swap_int( &spinlock->atomic_spin_variable_, &expected, 1)) { + if (0 == (spins & 1023)) { + embb_thread_yield(); + } + spins++; // reset expected, as CAS might change it... expected = 0; } diff --git a/base_cpp/include/embb/base/mutex.h b/base_cpp/include/embb/base/mutex.h index c700003..ac9b6fc 100644 --- a/base_cpp/include/embb/base/mutex.h +++ b/base_cpp/include/embb/base/mutex.h @@ -192,6 +192,9 @@ class Spinlock { /** * Waits until the spinlock can be locked and locks it. * + * \note This method yields the current thread in regular, + * implementation-defined intervals. + * * \pre The spinlock is not locked by the current thread. * \post The spinlock is locked. * \threadsafe