《计算机操作系统》_理解并发程序的执行_第4次课20250925
小技巧:如何隐藏linux命令行中的绝对路径
cd root
vim .bashrcexport PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '\u表示:用户名
\h表示:主机名
\$表示:终端提示符,$为一般用户,#为root用户把其中\w删除即可(.bashrc 改动后,需要输入 source .bashrc 才能立即生效)
小技巧:如何在vim编辑器中查找代码:
输入 【/】 后敲入【寻找内容】后敲击【enter】
1.互斥
1.1问题代码
保证两个线程可能会同时执行一段代码
实例代码如下:
#include "thread.h"unsigned long balance = 100;#define LOAD(x) x
#define STORE(x,y) (x) = (y)void Alipay_withdraw(int amt) {if (LOAD(balance) >= amt) {usleep(1); // unexpected delaysSTORE(balance,LOAD(balance) - amt);}
}void Talipay(int id) {Alipay_withdraw(100);
}int main() {create(Talipay);create(Talipay);join();printf("balance = %lu\n", balance);
}
小技巧:linux连续执行的shell语法:
你会得到几乎无限多的钱!
示例代码:
#include "thread.h"#define N 100000000
#define LOCK (0)
#define UNLOCK (1)long sum = 0;int locked = UNLOCK;void Tsum() {
retry:if(locked != UNLOCK){goto retry;}locked = LOCK;sum++;locked = UNLOCK;
}int main() {create(Tsum);create(Tsum);join();printf("sum = %ld\n", sum);
}
处理器默认不保证load+store的原子性(要么完全执行、要么完全不执行,即不可分割)
1.2正确性不明的奇怪尝试(peterson算法)
store(x)更改状态(举个旗子)
load(x)查看状态(查看旗子)
宿舍两个人上厕所(看似谦让,实则自私)
a上厕所,举起来a旗帜,查看对方的旗帜有没有举起来,在厕所写上了<给b用>
b上厕所,举起来b旗帜,查看对方的旗帜有没有举起来,在厕所写上了<给a用>
出隔间后,放下自己的旗帜。
#include "thread.h"#define A 1
#define B 2atomic_int nested;//原子性操作数,无需额外加锁就可以在多线程环境中安全访问
atomic_long count;//void critical_section() {long cnt = atomic_fetch_add(&count, 1);assert(atomic_fetch_add(&nested, 1) == 0);//(c、c++、python语言中的断言程序,非0无事发生,出现0在控制台输出错误信息)atomic_fetch_add(&nested, -1);//原子性操作函数,nested +=(-1)并返回nested更新前的值
}int volatile x = 0, y = 0, turn = A;void TA() {while (1) {
/* PC=1 */ x = 1;
/* PC=2 */ turn = B;
/* PC=3 */ while (y && turn == B) ;critical_section();
/* PC=4 */ x = 0;}
}void TB() {while (1) {
/* PC=1 */ y = 1;
/* PC=2 */ turn = A;
/* PC=3 */ while (x && turn == A) ;critical_section();
/* PC=4 */ y = 0;}
}int main() {create(TA);create(TB);
}
1.3小技巧:使用tmux软件可以实现命令行的上下、左右分屏;
安装tmux
sudo apt install tmux启动tmux:tmux垂直分屏:
ctrl + b
”左右分屏
ctrl + b
%关闭当前分屏:
ctrl + d退出tmux
exit光标切换到上方窗格
快捷键:Ctrl+b 方向键上