what's the difference between Rlock and Lock?

本文对比了Python中RLock与Lock两种同步机制的不同之处。RLock允许多次被同一个线程获取并需对应次数释放才能解锁,而Lock一旦释放即可被任一线程重新获取。通过示例展示了使用RLock解决函数间同步调用的问题。

来自StackOverflow上的问答:

The main difference is that a Lock can only be acquired once. It cannot be acquired again, until it is released. (After it's been released, it can be re-acaquired by any thread).

An RLock on the other hand, can be acquired multiple times, by the same thread. It needs to be released the same number of times in order to be "unlocked".

Another difference is that an acquired Lock can be released by any thread, while an acquired RLock can only be released by the thread which acquired it.


Here's an example demostrating why RLock is useful at times. Suppose you have:

def f():
  g()
  h()

def g():
  h()
  do_something1()

def h():
  do_something2()

Let's say all of fg, and h are public (i.e. can be called directly by an external caller), and all of them require syncronization.

Using a Lock, you can do something like:

lock = Lock()

def f():
  with lock:
    _g()
    _h()

def g():
  with lock:
    _g()

def _g():
  _h()
  do_something1()

def h():
  with lock:
    _h()

def _h():
  do_something2()

Basically, since f cannot call g after acquiring the lock, it needs to call a "raw" version of g (i.e. _g). So you end up with a "synced" version and a "raw" version of each function.

Using an RLock elegantly solves the problem:

lock = RLock()

def f():
  with lock:
    g()
    h()

def g():
  with lock:
    h()
    do_something1()

def h():
  with lock:
    do_something2()

MATLAB代码实现了一个基于多种智能优化算法优化RBF神经网络的回归预测模型,其核心是通过智能优化算法自动寻找最优的RBF扩展参数(spread),以提升预测精度。 1.主要功能 多算法优化RBF网络:使用多种智能优化算法优化RBF神经网络的核心参数spread。 回归预测:对输入特征进行回归预测,适用于连续值输出问题。 性能对比:对比不同优化算法在训练集和测试集上的预测性能,绘制适应度曲线、预测对比图、误差指标柱状图等。 2.算法步骤 数据准备:导入数据,随机打乱,划分训练集和测试集(默认7:3)。 数据归一化:使用mapminmax将输入和输出归一化到[0,1]区间。 标准RBF建模:使用固定spread=100建立基准RBF模型。 智能优化循环: 调用优化算法(从指定文件夹中读取算法文件)优化spread参数。 使用优化后的spread重新训练RBF网络。 评估预测结果,保存性能指标。 结果可视化: 绘制适应度曲线、训练集/测试集预测对比图。 绘制误差指标(MAE、RMSE、MAPE、MBE)柱状图。 十种智能优化算法分别是: GWO:灰狼算法 HBA:蜜獾算法 IAO:改进天鹰优化算法,改进①:Tent混沌映射种群初始化,改进②:自适应权重 MFO:飞蛾扑火算法 MPA:海洋捕食者算法 NGO:北方苍鹰算法 OOA:鱼鹰优化算法 RTH:红尾鹰算法 WOA:鲸鱼算法 ZOA:斑马算法
### Java 中 `ReentrantLock` 的 `tryLock()` 方法详解 #### 非阻塞锁获取方式 `tryLock()` 是一种非阻塞的方式来尝试获取锁。当调用此方法时,如果当前线程能够立即获得锁,则返回 `true`; 如果无法立即获得锁(即已经被其他线程持有),则立刻返回 `false`, 不会使当前线程进入等待状态[^2]。 #### 示例代码展示 下面给出一段利用 `tryLock()` 实现资源访问控制的例子: ```java import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class TryLockExample { private final Lock lock = new ReentrantLock(); public boolean accessResource() { if (lock.tryLock()) { // 尝试获取锁 try { System.out.println(Thread.currentThread().getName() + " acquired the lock."); // 模拟处理业务逻辑的时间消耗 try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return true; } finally { lock.unlock(); // 确保最终总是释放锁 } } else { System.out.println(Thread.currentThread().getName() + " failed to acquire the lock."); return false; } } public static void main(String[] args) throws InterruptedException { TryLockExample example = new TryLockExample(); Runnable task = () -> { for (int i = 0; i < 5; ++i) { example.accessResource(); } }; Thread t1 = new Thread(task, "Thread-1"); Thread t2 = new Thread(task, "Thread-2"); t1.start(); t2.start(); t1.join(); t2.join(); } } ``` 在这个例子中,两个不同的线程 (`t1` 和 `t2`) 同时竞争同一个锁对象。由于采用了 `tryLock()` 方式来请求锁,所以即使其中一个线程已经持有了该锁,在另一个线程试图获取相同锁的时候并不会被挂起而是直接得到失败的结果并继续执行后续操作。 #### 关于解锁行为 值得注意的是,只有成功获得了锁之后才应该去解除它;否则可能会抛出异常。这是因为对于未持有的锁进行解锁是没有意义的行为,并且违反了并发编程中的基本约定[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值