dpdk-spinlock

spinlock在多线程编程中经常被使用,我们经常叫无锁,底层的实现是汇编代码的compare-and-set,也就是CAS大法!!!

spinlock的操作:

typedef struct {
    volatile int locked; /**< lock status 0 = unlocked, 1 = locked */
} rte_spinlock_t;


//spinlock的初始化,lock=0,标识无锁状态
static inline void
rte_spinlock_init(rte_spinlock_t *sl)
{
    sl->locked = 0;
}

//加锁,也就是locked置1
static inline void
rte_spinlock_lock(rte_spinlock_t *sl)
{
    while (__sync_lock_test_and_set(&sl->locked, 1))
        while(sl->locked)
            rte_pause();
}

//解锁
static inline void
rte_spinlock_unlock (rte_spinlock_t *sl)
{
    __sync_lock_release(&sl->locked);
}

// 尝试加锁,如果当前状态是无锁,func返回1,标识加锁成功,失败func返回0
static inline int
rte_spinlock_trylock (rte_spinlock_t *sl)
{
    return (__sync_lock_test_and_set(&sl->locked,1) == 0);
}

//返回当前锁的status
static inline int rte_spinlock_is_locked (rte_spinlock_t *sl)
{
    return sl->locked;
}

下面两个func是gcc原子操作:

type __sync_lock_test_and_set (type *ptr, type value, ...)

将*ptr设为value, 并返回*ptr操作之前的值。

void __sync_lock_release (type *ptr, ...)

将*ptr置0

测试代码地址github

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值