PosixLibraryImplementationBasedF.MuellersPaper

上传人:re****.1 文档编号:587319695 上传时间:2024-09-05 格式:PPT 页数:46 大小:169KB
返回 下载 相关 举报
PosixLibraryImplementationBasedF.MuellersPaper_第1页
第1页 / 共46页
PosixLibraryImplementationBasedF.MuellersPaper_第2页
第2页 / 共46页
PosixLibraryImplementationBasedF.MuellersPaper_第3页
第3页 / 共46页
PosixLibraryImplementationBasedF.MuellersPaper_第4页
第4页 / 共46页
PosixLibraryImplementationBasedF.MuellersPaper_第5页
第5页 / 共46页
点击查看更多>>
资源描述

《PosixLibraryImplementationBasedF.MuellersPaper》由会员分享,可在线阅读,更多相关《PosixLibraryImplementationBasedF.MuellersPaper(46页珍藏版)》请在金锄头文库上搜索。

1、Posix Library ImplementationBased F. Muellers PaperLanguage ApplicationLanguage InterfaceC Language ApplicationPosix thread libraryUnix KernelUnix librariesUser LevelKernel Level1Pthread_join and Pthread_detach functionPthread_join(tid, .) : executing threads blocks waiting for the thread tid to exi

2、t.Pthread_detach(tid,.): request reclaiming of the resources of the thread tid, if it has completed. ( This is more to take some implementation variations).2Inter-Process Communication and SynchronizationB. Ramamurthy3IntroductionAn important and fundamental feature in modern operating systems is co

3、ncurrent execution of processes/threads. This feature is essential for the realization of multiprogramming, multiprocessing, distributed systems, and client-server model of computation.Concurrency encompasses many design issues including communication and synchronization among processes, sharing of

4、and contention for resources.In this discussion we will look at the various design issues/problems and the wide variety of solutions available.4Topics for discussionThe principles of concurrencyInteractions among processesMutual exclusion problemMutual exclusion- solutionsSoftware approaches (Dekker

5、s and Petersons)Hardware support (test and set atomic operation)OS solution (semaphores)PL solution (monitors)Distributed OS solution ( message passing)Reader/writer problemDining Philosophers Problem5Principles of ConcurrencyInterleaving and overlapping the execution of processes.Consider two proce

6、sses P1 and P2 executing the function echo: input (in, keyboard); out = in; output (out, display);6.Concurrency (contd.)P1 invokes echo, after it inputs into in , gets interrupted (switched). P2 invokes echo, inputs into in and completes the execution and exits. When P1 returns in is overwritten and

7、 gone. Result: first ch is lost and second ch is written twice.This type of situation is even more probable in multiprocessing systems where real concurrency is realizable thru multiple processes executing on multiple processors.Solution: Controlled access to shared resourceProtect the shared resour

8、ce : in buffer; “critical resource”one process/shared code. “critical region”7Interactions among processesIn a multi-process application these are the various degrees of interaction:1. Competing processes: Processes themselves do not share anything. But OS has to share the system resources among the

9、se processes “competing” for system resources such as disk, printer. Co-operating processes : Results of one or more processes may be needed for another process. 2. Co-operation by sharing : Example: Sharing of an IO buffer. Concept of critical section. (indirect)3. Co-operation by communication : E

10、xample: typically no data sharing, but co-ordination thru synchronization becomes essential in certain applications. (direct)8Interactions .(contd.)Among the three kinds of interactions indicated by 1, 2 and 3 above:1 is at the system level: potential problems : deadlock and starvation.2 is at the p

11、rocess level : significant problem is in realizing mutual exclusion.3 is more a synchronization problem.We will study mutual exclusion and synchronization here, and defer deadlock, and starvation for a later time.9Race ConditionRace condition: The situation where several processes access and manipul

12、ate shared data concurrently. The final value of the shared data depends upon which process finishes last.To prevent race conditions, concurrent processes must be synchronized.10Mutual exclusion problemSuccessful use of concurrency among processes requires the ability to define critical sections and

13、 enforce mutual exclusion.Critical section : is that part of the process code that affects the shared resource.Mutual exclusion: in the use of a shared resource is provided by making its access mutually exclusive among the processes that share the resource.This is also known as the Critical Section

14、(CS) problem.11Mutual exclusionAny facility that provides mutual exclusion should meet these requirements: 1. No assumption regarding the relative speeds of the processes.2. A process is in its CS for a finite time only.3. Only one process allowed in the CS.4. Process requesting access to CS should

15、not wait indefinitely.5. A process waiting to enter CS cannot be blocking a process in CS or any other processes.12Software Solutions: Algorithm 1Process 0.while turn != 0 do nothing;/ busy waitingturn = 1;.Problems : Strict alternation, Busy WaitingProcess 1.while turn != 1 do nothing;/ busy waitin

16、gturn = 0;.13Algorithm 2PROCESS 0.flag0 = TRUE;while flag1 do nothing;flag0 = FALSE;PROBLEM : Potential for deadlock, if one of the processes fail within CS.PROCESS 1.flag1 = TRUE;while flag0 do nothing;flag1 = FALSE;14Algorithm 3Combined shared variables of algorithms 1 and 2.Process Pido flag i:=

17、true;turn = j;while (flag j and turn = j) ;critical sectionflag i = false;remainder section while (1);Solves the critical-section problem for two processes.15Synchronization HardwareTest and modify the content of a word atomically.boolean TestAndSet(boolean &target) boolean rv = target;target = true

18、;return rv;16Mutual Exclusion with Test-and-SetShared data: boolean lock = false;Process Pido while (TestAndSet(lock) ;critical sectionlock = false;remainder section17Synchronization Hardware Atomically s variables.void S &a, boolean &b) boolean temp = a;a = b;b = temp;18Mutual Exclusion with SwapSh

19、ared data (initialized to false): boolean lock;Process Pido key = true;while (key = true) S);critical sectionlock = false;remainder section19Semaphores Think about a semaphore as a classAttributes: semaphore value, Functions: init, wait, signalSupport provided by OSConsidered an OS resource, a limit

20、ed number available: a limited number of instances (objects) of semaphore class is allowed.Can easily implement mutual exclusion among any number of processes.20Critical Section of n ProcessesShared data: Semaphore mutex; /initially mutex = 1Process Pi: do mutex.wait(); critical section mutex.signal

21、(); remainder section while (1); 21Semaphore ImplementationDefine a semaphore as a class:class Semaphore int value; / semaphore value ProcessQueue L; / process queue /operationswait()signal()In addition, two simple utility operations:block() suspends the process that invokes it.Wakeup() resumes the

22、execution of a blocked process P.22Semantics of wait and signalSemaphore operations now defined as S.wait():S.value-;if (S.value 0) add this process to S.L;block(); / block a processS.signal(): S.value+;if (S.value = 0) remove a process P from S.L;wakeup(); / wake a process23 Semaphores for CSSemaph

23、ore is initialized to 1. The first process that executes a wait() will be able to immediately enter the critical section (CS). (S.wait() makes S value zero.) Now other processes wanting to enter the CS will each execute the wait() thus decrementing the value of S, and will get blocked on S. (If at a

24、ny time value of S is negative, its absolute value gives the number of processes waiting blocked. )When a process in CS departs, it executes S.signal() which increments the value of S, and will wake up any one of the processes blocked. The queue could be FIFO or priority queue.24Two Types of Semapho

25、resCounting semaphore integer value can range over an unrestricted domain.Binary semaphore integer value can range only between 0 and 1; can be simpler to implement. ex: nachosCan implement a counting semaphore using a binary semaphore.25Semaphore for SynchronizationExecute B in Pj only after A exec

26、uted in PiUse semaphore flag initialized to 0Code:PiPj Aflag.wait()flag.signal()B26Classical Problems of SynchronizationBounded-Buffer ProblemReaders and Writers ProblemDining-Philosophers Problem27Producer/Consumer problemProducerrepeatproduce item v;bin = v;in = in + 1;forever;Consumerrepeatwhile

27、(in = out) nop;w = bout;out = out + 1;consume w;forever;28Solution for P/C using Semaphores Producerrepeatproduce item v;MUTEX.wait();bin = v;in = in + 1;MUTEX.signal();forever;What if Producer is slow or late?Consumerrepeatwhile (in = out) nop;MUTEX.wait();w = bout;out = out + 1;MUTEX.signal();cons

28、ume w;forever;Ans: Consumer will busy-wait at the while statement.29P/C: improved solution Producerrepeatproduce item v;MUTEX.wait();bin = v;in = in + 1;MUTEX.signal();AVAIL.signal();forever;What will be the initial values of MUTEX and AVAIL?ConsumerrepeatAVAIL.wait();MUTEX.wait();w = bout;out = out

29、 + 1;MUTEX.signal();consume w;forever;ANS: Initially MUTEX = 1, AVAIL = 0.30P/C problem: Bounded bufferProducerrepeatproduce item v;while(in+1)%n = out) NOP;bin = v;in = ( in + 1)% n;forever;How to enforce bufsize?Consumerrepeatwhile (in = out) NOP;w = bout;out = (out + 1)%n;consume w;forever;ANS: U

30、sing another counting semaphore.31P/C: Bounded Buffer solutionProducerrepeatproduce item v;BUFSIZE.wait();MUTEX.wait();bin = v;in = (in + 1)%n;MUTEX.signal();AVAIL.signal();forever;What is the initial value of BUFSIZE?ConsumerrepeatAVAIL.wait();MUTEX.wait();w = bout;out = (out + 1)%n;MUTEX.signal();

31、BUFSIZE.signal();consume w;forever;ANS: size of the bounded buffer.32Semaphores - commentsIntuitively easy to use.wait() and signal() are to be implemented as atomic operations.Difficulties: signal() and wait() may be exchanged inadvertently by the programmer. This may result in deadlock or violatio

32、n of mutual exclusion.signal() and wait() may be left out.Related wait() and signal() may be scattered all over the code among the processes.33MonitorsMonitor is a predecessor of the “class” concept.Initially it was implemented as a programming language construct and more recently as library. The la

33、tter made the monitor facility available for general use with any PL.Monitor consists of procedures, initialization sequences, and local data. Local data is accessible only thru monitors procedures. Only one process can be executing in a monitor at a time. Other process that need the monitor wait su

34、spended.34Monitorsmonitor monitor-nameshared variable declarationsprocedure body P1 () . . .procedure body P2 () . . . procedure body Pn () . . . initialization code35MonitorsTo allow a process to wait within the monitor, a condition variable must be declared, ascondition x, y;Condition variable can

35、 only be used with the operations wait and signal.The operationx.wait();means that the process invoking this operation is suspended until another process invokesx.signal();The x.signal operation resumes exactly one suspended process. If no process is suspended, then the signal operation has no effec

36、t.36Schematic View of a Monitor37Monitor With Condition Variables38Message passingBoth synchronization and communication requirements are taken care of by this mechanism. More over, this mechanism yields to synchronization methods among distributed processes.Basic primitives are: send (destination,

37、message);receive ( source, message);39 Issues in message passingSend and receive: could be blocking or non-blocking:Blocking send: when a process sends a message it blocks until the message is received at the destination.Non-blocking send: After sending a message the sender proceeds with its process

38、ing without waiting for it to reach the destination.Blocking receive: When a process executes a receive it waits blocked until the receive is completed and the required message is received. Non-blocking receive: The process executing the receive proceeds without waiting for the message(!).Blocking R

39、eceive/non-blocking send is a common combination.40Reader/Writer problemData is shared among a number of processes.Any number of reader processes could be accessing the shared data concurrently.But when a writer process wants to access, only that process must be accessing the shared data. No reader

40、should be present.Solution 1 : Readers have priority; If a reader is in CS any number of readers could enter irrespective of any writer waiting to enter CS.Solution 2: If a writer wants CS as soon as the CS is available writer enters it.41Reader/writer: Priority ReadersWriter:ForCS.wait();CS;ForCS.s

41、ignal();Reader:ES.wait();NumRdr = NumRdr + 1;if NumRdr = 1 ForCS.wait();ES.signal();CS;ES.wait();NumRdr = NumRdr -1;If NumRdr = 0 ForCS.signal();ES.signal();42Dining Philosophers Examplemonitor dp enum thinking, hungry, eating state5;condition self5;void pickup(int i) / following slidesvoid putdown(

42、int i) / following slidesvoid test(int i) / following slidesvoid init() for (int i = 0; i 5; i+)statei = thinking;43Dining Philosophersvoid pickup(int i) statei = hungry;testi;if (statei != eating)selfi.wait();void putdown(int i) statei = thinking;/ test left and right neighborstest(i+4) % 5);test(i

43、+1) % 5);44Dining Philosophersvoid test(int i) if ( (state(I + 4) % 5 != eating) & (statei = hungry) & (state(i + 1) % 5 != eating) statei = eating;selfi.signal();45SummaryWe looked at various ways/levels of realizing synchronization among concurrent processes.Synchronization at the kernel level is usually solved using hardware mechanisms such as interrupt priority levels, basic hardware lock, using non-preemptive kernel (older BSDs), using special signals.46

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 资格认证/考试 > 自考

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号