自旋锁
下面的代码实现了一个简陋的自旋锁。
由于仅仅是用于实验的原型代码,
所以可能包含许多错误和不适当的地方。
如果在信号处理函数中使用该锁,
可能会死锁。
该代码用于linux环境,在fedora11中测试过。
spin_lock.h:
=========================================================================
// 2011年 09月 13日 星期二 10:43:03 cst
// author: 李小丹(li shao dan) 字 殊恒(shuheng)
// k.i.s.s
// s.p.o.t
#ifndef mem_lock_h
#define mem_lock_h
#include <unistd.h>
#include <sched.h>
#include <sys/syscall.h>
#if ((defined(__gnuc__) && \
((__gnuc__ > 4 || (__gnuc__ == 4 && __gnuc_minor__ >= 1)))))
//#if 0
#pragma message "builtin on intel"
#define atomic_test_and_set(a) __sync_lock_test_and_set(a, 1)
#define atomic_clear(a) __sync_lock_release(a);
#elif (defined(__i386__) || defined(__x86_64__))
#pragma message "not builtin on intel"
inline static unsigned long
atomic_test_and_set(volatile unsigned long *a)
{
const unsigned long n = 1, old = 0;
unsigned long ret;
__asm__ __volatile__ (
" lock; "
" cmpxchgl %3, %1; "
: "=a" (ret)
: "m" (*a), "a" (old), "r" (n)
: "memory", "cc"
);
return ret;
}
inline static void atomic_clear(volatile unsigned long *a)
{
assert(*a);
unsigned long ret, n = 0;
__asm__ __volatile__ (
" lock; "
"xchgl %0, %1"
: "=r" (ret)
: "m" (*a), "0" (n)
: "memory"
);
}
#endif
typedef struct {
volatile unsigned long tid;
volatile unsigned long lock;
volatile unsigned long recur;
} spin_lock_t;
inline static void spin_lock_init(spin_lock_t *);
inline static int spin_lock_lock(spin_lock_t *);
inline static int spin_lock_unlock(spin_lock_t *);
inline static void spin_lock_init(spin_lock_t *lk)
{
lk->tid = 0;
lk->lock = 0;
lk->recur = 0;
}
#define spin_yield_interval 63u
inline static int spin_lock_lock(spin_lock_t *lk)
{
pid_t now = syscall(sys_gettid);
int c = 0;
for(;;) {
if(!atomic_test_and_set(&lk->lock)) {
// xxx: at the moment,
// receive a signal and signal handler use the spin lock,
// dead lock;
lk->tid = (unsigned long)now;
lk->recur = 1;
return 0;
}
if(lk->tid == (unsigned long)now)
return ++lk->recur;
if(!(++c & spin_yield_interval))
sched_yield();
}
return 0;
}
inline static int spin_lock_unlock(spin_lock_t *lk)
{
unsigned long now =
(unsigned long)syscall(sys_gettid);
if(lk->tid != now)
return -1;
if(!--lk->recur) {
lk->tid = 0;
atomic_clear(&lk->lock);
}
return 0;
}
#endif
摘自 leeshuheng的专栏
下一篇: C/C++中的#与##