




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1、1Chapter 2Processes and Threads2.1 Processes2.2 Threads2.3 Inter-process communication2.4 Classical IPC problems2.5 Scheduling2Inter-process CommunicationvThree issues are involved in inter-process communication (IPC)1.How one process can pass information to another.2.Resource shared (e.g. printer)H
2、ow to make sure two or more processes do not get into each others way when engaging in critical activities. 3.Process cooperationProper sequencing when dependencies are present.3Process Synchronizationv進程同步:對多個相關進程在執(zhí)行次序上的協調,用于保證這種關系的相應機制稱為進程同步。(或相互合作的一組并發(fā)進程在一些關鍵點上可能需要互相等待與互通消息,這種相互制約的等待與互通消息稱為進程同步。)
3、v例:醫(yī)生為病員診病,認為需要化驗,開出化驗單。病員取樣送到化驗室,等化驗完畢交給醫(yī)生化驗結果,繼續(xù)診病。醫(yī)生診病是一個進程,化驗室的化驗工作是另一個進程,它們各自獨立的活動,但又共同完成醫(yī)療任務?;炦M程只有在接收到診病進程的化驗單后才開始工作;而診病進程只有獲得化驗結果后才能繼續(xù)為該病員診病,并根據化驗結果確定醫(yī)療方案。v例:計算進程與打印進程共享一個單緩沖區(qū)的問題。4Spooling Example: CorrectSpooler DirectoryabcProg.cProg.n4567F2outinProcess 1Process 2next_free = in;next_free =
4、 inint next_free;Stores F1 into next_free;Stores F2 into next_free;int next_free;124in=next_free+1F1in=next_free+1356895Spooling Example: RacesShared memoryabcProg.cProg.n4567outinProcess 1Process 2next_free = in;/* value: 7 */next_free = in/* value: 7 */int next_free;Stores F1 into next_free;Stores
5、 F2 into next_free;int next_free;152in=next_free+1F1in=next_free+1634F26Mutual exclusionSome way of making sure that if one process is using a shared variable or file, the other processes will be excluded from doing the same thing.Race conditionsRace conditions are situations in which several proces
6、ses access shared data and the final result depends on the order of operations.The key to avoid race conditions is to prohibit more than one process from reading and writing the shared data at the same time.7vCritical Resource(臨界資源)一次僅允許一個進程訪問的資源稱為臨界資源臨界資源包括:硬件資源:輸入機、打印機等軟件資源:變量、表格、隊列、文件等vCritical R
7、egion (Critical Section)The part of the program where the critical resource is accessed is called critical region or critical section.If we could arrange matters such that no two processes were ever in their critical regions at the same time, we could avoid races.8程 序 段1程 序 段2程 序 段n共 享 變 量9a := a -1
8、 print (a)a := a +1 print (a)P1P2If a 0then a := a +1else a:= a-1P3Mutual exclusionentry sectionexit section critical section remainder section10Critical Region RequirementvFour conditions to provide mutual exclusion1.No two processes simultaneously in critical region2.No assumptions made about spee
9、ds or numbers of CPUs3.No process running outside its critical region may block another process4.No process must wait forever to enter its critical region11Mutual exclusion using critical regions12Mutual ExclusionvPossible Solutions Disabling Interrupts Lock Variables Strict Alternation Petersons so
10、lution TSL Sleep and Wakeup13Solution 1 - Disabling Interrupts How does it work? Disable all interrupts just after entering a critical section and re-enable them just before leaving it. Why does it work? With interrupts disabled, no clock interrupts can occur. (The CPU is only switched from one proc
11、ess to another as a result of clock or other interrupts, and with interrupts disabled, no switching can occur.) Problems: What if the process forgets to enable the interrupts? Multiprocessor? (disabling interrupts only affects one CPU) Only used inside OS14Solution 2 - Lock Variable shared int lock
12、= 0;/* entry_code: execute before entering critical section */while (lock != 0) /* do nothing */ ;lock = 1; - critical section -/* exit_code: execute after leaving critical section */lock = 0;This solution may violate property 1. If a context switch occurs after one process executes the while statem
13、ent, but before setting lock = 1, then two (or more) processes may be able to enter their critical sections at the same time.15Solution 3 - Strict AlternationThis solution may violate property 3. Since the processes must strictly alternate entering their critical sections, a process wanting to enter
14、 its critical section twice in a row will be blocked until the other process decides to enter (and leave) its critical section.16Solution 4 - Petersonsenter_region ( i );Critical regionleave_region ( i );Noncritical regionprocess i17Solution 4 - PetersonsPetersons solution for achieving mutual exclu
15、sion18Hardware solution 5: Test-and-Set Locks (TSL)The hardware must support a special instruction, tsl, which does 2 things in a single atomic action: tsl register, flag(a) copy a value in memory (flag) to a CPU register (b) set flag to 1.19Test-and-Set Locks (TSL)Entering and leaving a critical re
16、gion using the TSL instruction返回20Test-and-Set Locks (TSL)Entering and leaving a critical region using the XCHG instruction.21Mutual Exclusion with Busy WaitingvThe last two solutions, 4 and 5, require BUSY-WAITING; that is, a process executing the entry code will sit in a tight loop using up CPU cy
17、cles, testing some condition over and over, until it becomes true. vBusy-waiting may lead to the PRIORITY-INVERSION PROBLEM if simple priority scheduling is used to schedule the processes.22Mutual Exclusion with Busy WaitingvExample: Test-and-set Locks: P0 (low) - in cs -x | context switch | P1 (hig
18、h) -tsl-cmp-jnz-tsl. x-tsl-cmp. x-. forever.vNote, since priority scheduling is used, P1 will keep getting scheduled and waste time doing busy-waiting. :-( vThus, we have a situation in which a low-priority process is blocking a high-priority process, and this is called PRIORITY-INVERSION.23Sleep an
19、d WakeupvSolution of previous problems: sleep and wakeup(busy waiting)Block instead of busy waiting when it is not allowed to enter the Critical Region (sleep)Wakeup when it is OK to retry entering the critical region24Producer-Consumer Problem (Bounded-buffer problem )vConsider two processes share
20、a circular buffer that can hold N items.vProducers add items to the buffer and Consumers remove items from the buffer. vThe Producer-Consumer Problem is to restrict access to the buffer so correct executions result.25Sleep and WakeupProducer-consumer problem with fatal race conditionSwitch to produc
21、er26Semaphores (E.W. Dijkstra,1965)vA SEMAPHORE, S, is a structure consisting of two parts: (a) an integer counter, COUNT (b) a queue of pids of blocked processes, QvThat is, struct sem_struct int count; queue Q; semaphore;semaphore S;27Semaphores vA semaphore count represents count number of abstra
22、ct resourcesCounting semaphores: 0.NBinary semaphores: 0,1vThere are 2 operations on semaphoresThe Down (P) operation is used to acquire a resource and decrements count. The Up (V) operation is used to release a resource and increments count. vAny semaphore operation is indivisible, must be executed
23、 atomically. (what is primitive?) 28SemaphoresvSuppose that P is the process making the down and up system calls. The operations are defined as follows:P操作操作 DOWN(S): S.count = S.count - 1; /apply for a resource if (S.count 0) /if no resourceblock(P); (a) enqueue the pid of P in S.Q,(b) block proces
24、s P (remove the pid from the ready queue), and(c) pass control to the scheduler. 執(zhí)行一次P操作后,若S.count0,則|S.count|等于Q隊列中等待S資源的進程數。29SemaphoresV操作操作 UP(S): S.count = S.count + 1; /release a resource if ( S.count0表示有S.count個資源可用 S.count=0表示無資源可用 S.count0則|S.count|表示S等待隊列中的進程個數 P(S):表示申請一個資源 V(S):表示釋放一個資源。
25、信號量的初值應該大于等于02) P,V操作必須成對出現,有一個P操作就一定有一個V操作當為互斥操作時,它們同處于同一進程;當為同步操作時,則不在同一進程中出現。如果P(S1)和P(S2)兩個操作在一起,那么P操作的順序至關重要,一個同步P操作與一個互斥P操作在一起時同步P操作在互斥P操作前;而兩個V操作的順序無關緊要。討論:討論:453) 信號量同步的缺點用信號量可實現進程間的同步,但由于信號量的控制分布在整個程序中,其正確性分析很困難。4) 引入管程 1973年,Hoare和Hanson提出一種高級同步原語管程; 其基本思想是把信號量及其操作原語封裝在一個對象內部。 管程是管理進程間同步的機
26、制,它保證進程互斥地訪問共享變量,并方便地阻塞和喚醒進程。 管程可以函數庫的形式實現。相比之下,管程比信號量好控制。46MonitorsvA monitor is a collection of procedures, variables, and data structures that can only be accessed by one process at a time (for the purpose of mutual exclusion). vTo allow a process to wait within the monitor, a condition variable
27、must be declared, as condition x, y;vCondition variable can only be used with the operations wait and signal (for the purpose of synchronization).The operationwait(x);means that the process invoking this operation is suspended until another process invokessignal(x);The signal(x) operation resumes ex
28、actly one suspended process. If no process is suspended, then the signal operation has no effect.47MonitorsExample of a monitor48MonitorsOutline of producer-consumer problem with monitorsonly one monitor procedure active at one timebuffer has N slots49Message passingPossible Approaches of IPC:1) Sha
29、red memory2) Shared file mode;pipe: is a shared filevOne end is for reading and one end is for writing.3) Message passing: primitive: send and receivevAssign each process a unique address such as addr. Then, send messages directly to the process: send(addr, msg); recv(addr, msg);vUse mailboxes: send
30、(mailbox, msg); recv(mailbox, msg);50Message PassingThe producer-consumer problem with N messages51BarriersvUse of a barriera)processes approaching a barrierb)all processes but one blocked at barrierc)last process arrives, all are let throughvExample: Parallel matrix multiplication52Classical IPC Pr
31、oblemsvThese problems are used for testing every newly proposed synchronization scheme:Bounded-Buffer (Producer-Consumer) ProblemDining-Philosophers ProblemReaders and Writers Problem53Dining PhilosophersvDining Philosophers Problem Dijkstra, 1965: Problem: Five philosophers are seated around a tabl
32、e. There is one fork between each pair of philosophers. Each philosopher needs to grab the two adjacent forks in order to eat. Philosophers alternate between eating and thinking. They only eat for finite periods of time.54vPhilosophers eat/thinkvEating needs 2 forksvPick one fork at a time vHow to p
33、revent deadlock Dining Philosophers55Dining PhilosophersA nonsolution to the dining philosophers problem56Dining PhilosophersvProblem: Suppose all philosophers execute the first DOWN operation, before any have a chance to execute the second DOWN operation; that is, they all grab one fork. Then, dead
34、lock will occur and no philosophers will be able to proceed. This is called a CIRCULAR WAIT.vOther Solutions:Only allow up to four philosophers to try grabbing their forks.Asymmetric solution: Odd numbered philosophers grab their left fork first, whereas even numbered philosophers grab their right fork first.Protect the five statements following think() by mutexPick-up the forks only if both are available. See F
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 農業(yè)產業(yè)鏈安全監(jiān)管方案手冊
- 離婚財產公證協議書
- 風力發(fā)電場項目投資合同
- 第八單元-第4課時-認識垂直(教學設計)四年級數學上冊同步高效課堂系列(蘇教版)
- 2025年愛康國賓項目建議書
- 第3課 項目一《校園護綠小能手·校園綠地護養(yǎng)院》(教學設計)-2023-2024學年三年級下冊綜合實踐活動浙教版
- 第15課 現代醫(yī)療衛(wèi)生體系與社會生活 教學設計 -2023-2024學年統編版(2019)高二歷史選擇性必修2 經濟與社會生活
- 溫度傳感器信號線施工方案
- 大單元學習 教學設計 2023-2024學年統編版高中語文選擇性必修下冊
- 浙教版2023小學信息技術六年級下冊《控制的形態(tài)》教學設計及反思
- 2023年高考真題-地理(遼寧卷) 含解析
- 搶救車的管理課件
- GB/T 38153.1-2024印刷技術測試印樣的實驗室制備第1部分:漿狀油墨
- 2024高考物理考試大綱
- 《上市公司財務舞弊探究的國內外文獻綜述》5000字
- 2024年護師類之護士資格證考試題庫
- 2024年公用設備工程師(給排水)《公共基礎》強化練習高分通關題庫600題(含答案)
- 腰椎間盤突出癥課件(共100張課件)
- 林學概論完整版本
- GB/T 44458.3-2024運動用眼部和面部保護第3部分:水面游泳用眼鏡的要求和試驗方法
- 學校食堂菜譜及定價方案
評論
0/150
提交評論