无锁编程(LOCK-FREE PROGRAMMING)

无锁编程是一种在多线程环境下避免使用互斥量等同步原语实现线程安全的技术。它涉及到CAS(CompareandSwap)操作,用于原子性地更新数据,以防止数据在读取、计算和写回期间被改变。然而,无锁编程也面临ABA问题,即在并发操作中可能出现的数据状态回滚。此外,文章提到了非阻塞队列和Java中的并发包(java.util.concurrent)作为无锁实现的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单介绍

锁的一些问题

CMU lock free pdf

什么样的程序是无锁编程

Thread-safe access to shared data without the use of synchronization primitives such as mutexes. It is possible but not practical in the absence of hardware support

  • 有多个threads(线程或进程)
  • 访问共享区域
  • threads之间不能block彼此
    Designing generalized lock-free algorithms is hard. Design lock-free data structures instead: buffer, list, stack, queue, map, deque, snapshot
ABA问题

Thread 1 基于变量x=A的基础上做了一系列操作,然而Thread 2将x改为了B。 如果Thread 1进行compare-and-set的话,会发现x已改变,撤回其进行的一系列操作。但是在这之前Thread 2又将变量变回了A!这导致Thread 1在x=B的情况下进行了一系列不合法的操作!

CMU的PDF有点抽象啊!!!

CAS(Compare and swap)

链接1
链接2
先比较输入的当前值和内存中的值是否一致,不一致则代表内存数据发生了变化,CAS失败。
就是防止在 读-计算-写 的这个过程中,原本读的值在写之前被改变。
CAS is an atomic operation, which means that fetch and update together are one single operation:
在这里插入图片描述
The important thing here is that CAS does not acquire a lock on the data structure but returns true if the update was successful, otherwise it returns false. The hardware should support compare-and-swap, to make it a truly atomic operation without the use of locking.

How CAS can be called:

void testCas() {
    int v = value;
    int x = v + 1;

    while(!cas(v, x)) {
        v = value;
        x = v + 1;
    }
}
Load-link/store-conditional
Fetch and Add
Non-Blocking Queue

就是用CAS基础做判断。

Wait-Free Queue
java中使用free lock: java.util.concurrent package

这个类超级大 非常不妙啊

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值