2.3 进 程 同 步
2.3.1 进程同步的基本概念
1.两种形式的制约关系
在多道程序环境下,当程序并发执行时,由于资源共享和进程合作,使同处于一个系统中的诸进程之间可能存在着以下两种形式的制约关系。
(1) 间接相互制约关系。源于共享着某种系统资源,如共享CPU、共享I/O设备等。(A请求正在被B进程占用的打印服务)
(2) 直接相互制约关系。源于进程间的合作。(B需要A进程向其提供数据)
2. 临界资源(Critical Resouce)(如打印机、磁带机等) 互斥访问
生产者和消费者进程的描述中
noop是一条空操作指令,while condition do no-op语句表示重复的测试条件(condication),重复测试应进行到该条件变为false(假)。
生产者进程中nextp,用于暂时存放每次刚生产出来的产品;
消费者进程中nextc,用于存放每次要消费的产品。
3.临界区
repeat
entry section //进入区 - 检查代码,对临界资源进行检查
critical section; //临界区(互斥访问
exit section //退出区 - 临界区正被访问的标志恢复为未被访问
remainder section;
until false;
4.同步机制应遵循的规则(协调各进程间的运行)
同步机制都应遵循下述四条准则:
(1) 空闲让进。
(2) 忙则等待。
(3) 有限等待。(保证在有限时间内能进入自己的临界区,以免陷入“死等”状态)。
(4) 让权等待。(不能进入自己的临界区时,立即释放处理机,以免进程陷入“忙等”状态)。
*2.3.2 信号量机制
1.整型信号量
wait(S): while S<=0 do no-op;
S:=S-1;//wait - 即P操作
signal(S):S:=S+1; //signal - V操作
2.记录型信号量
type semaphore=record
value: integer;
L: list of process;
end
相应地,wait(S)和signal(S)操作可描述为:
procedure wait(S)
var S:semaphore;
begin
S.value:=S.value-1;
if S.value<0 then block(S.L);
end
procedure signal(S)
var S: semaphore;
begin
S.value:=S.value+1;
if S.value<=0 then wakeup(S.L);
end
3.AND型信号量
Swait(S1,S2,…,Sn)
if Si>=1 and … and Sn>=1 then
for i:=1 to n do
Si:=Si-1;
endfor
else
place the process in the waiting queue associated with the first Si foundwith Si<1,and set the program count of this process to the beginning ofSwait operation
endif
Ssignal(S1,S2,…,Sn)
for i:=1 to n do
Si:=Si+1;
Remove all the process waiting in the queue associated with Si into the ready queue.
endfor;
4.信号量集
Swait(S1,t1,d1,…,Sn,tn,dn)
if Si>=t1 and … and Sn>=tn then
for i:=1 to n do
Si:=Si-di;
endfor
else
Place the executing process in the waiting queue of the first Si with Si<tiand set its program counter to the beginning of the Swait Operation.
endive
Ssignal(S1,d1,…,Sn,dn)
for i:=1 to n do
Si:=Si+di;
Remove all the process waiting in the queue associated with Si into the ready queue
endfor;
原创文章如转载请注明:转自¥忘%风 {http://www.cnblogs.com/slave_wc}
本文地址: 第二章-进程管理笔记(3)