赞
踩
应对bug的方法
在代码里边增加很多检查(加断言)
#include "thread.h" unsigned long balance = 100; void Alipay_withdraw(int amt) { if (balance >= amt) { usleep(1); // unexpected delays balance -= amt; } assert(balance <= 10000000); } void Talipay(int id) { Alipay_withdraw(100); } int main() { create(Talipay); create(Talipay); join(); printf("balance = %lu\n", balance); }
防御性编程:把程序需要满足的条件用 assert 表达出来。
assert()
并发bug:死锁 (Deadlock)
A deadlock is a state in which each member of a group is waiting for another member, including itself, to take action.
ABBA-Deadlock
void swap(int i, int j) {
spin_lock(&lock[i]);
spin_lock(&lock[j]);
arr[i] = NULL;
arr[j] = arr[i];
spin_unlock(&lock[j]);
spin_unlock(&lock[i]);
}
上锁的顺序很重要……
swap
本身看起来没有问题,swap(1, 2)
; swap(2, 3)
, swap(3, 1)
→ 死锁避免死锁
死锁产生的四个必要条件
AA-Deadlock
if (holding(lk)) panic();
ABBA-Deadlock
任意时刻系统中的锁都是有限的
严格按照固定的顺序获得所有锁 (lock ordering; 消除 “循环等待”)
class LockOrdering:
locks = [ '', '', '' ]
def tryacquire(self, lk):
self.locks[lk], seen = '声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/557194
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。