From 05af5d856c105c66efee0f22dfe5bc5ff45c3511 Mon Sep 17 00:00:00 2001 From: Oliver Kowalke Date: Sun, 3 Nov 2013 13:58:40 +0100 Subject: [PATCH] some improved spinlock --- src/detail/spinlock.cpp | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/detail/spinlock.cpp b/src/detail/spinlock.cpp index ebbc018b..38b4a8d7 100644 --- a/src/detail/spinlock.cpp +++ b/src/detail/spinlock.cpp @@ -22,13 +22,24 @@ spinlock::spinlock() : void spinlock::lock() { - while ( LOCKED == state_.exchange( LOCKED) ) + for (;;) { - // busy-wait - if ( scheduler::instance()->active() ) - scheduler::instance()->yield(); - else - this_thread::yield(); + // access to CPU's cache + // first access to state_ -> cache miss + // sucessive acccess to state_ > cache hit + while ( LOCKED == state_) + { + // busy-wait + if ( scheduler::instance()->active() ) + scheduler::instance()->yield(); + else + this_thread::yield(); + } + // state_ was released by other + // cached copies are invalidated -> cache miss + // test-and-set over the bus + if ( UNLOCKED == state_.exchange( LOCKED) ) + return; } }