 Wind River Systems, Inc. 1997 Chapter - 6 Semaphores.

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee.
1 Chapter 5 Concurrency: Mutual Exclusion and Synchronization Principals of Concurrency Mutual Exclusion: Hardware Support Semaphores Readers/Writers Problem.
Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Resource management and Synchronization Akos Ledeczi EECE 354, Fall 2010 Vanderbilt University.
CprE 458/558: Real-Time Systems (G. Manimaran)1 CprE 458/558: Real-Time Systems Resource Access Control Protocols.
Chapter 6: Process Synchronization
Background Concurrent access to shared data can lead to inconsistencies Maintaining data consistency among cooperating processes is critical What is wrong.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
EEE 435 Principles of Operating Systems Interprocess Communication Pt II (Modern Operating Systems 2.3)
Mutual Exclusion.
Secure Operating Systems Lesson 5: Shared Objects.
Interprocess Communication
Avishai Wool lecture Introduction to Systems Programming Lecture 4 Inter-Process / Inter-Thread Communication.
5.6 Semaphores Semaphores –Software construct that can be used to enforce mutual exclusion –Contains a protected variable Can be accessed only via wait.
5.6.2 Thread Synchronization with Semaphores Semaphores can be used to notify other threads that events have occurred –Producer-consumer relationship Producer.
Synchronization Principles. Race Conditions Race Conditions: An Example spooler directory out in 4 7 somefile.txt list.c scores.txt Process.
Concurrency: Mutual Exclusion, Synchronization, Deadlock, and Starvation in Representative Operating Systems.
Chapter 2.3 : Interprocess Communication
1 Concurrency: Deadlock and Starvation Chapter 6.
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
Instructor: Umar KalimNUST Institute of Information Technology Operating Systems Process Synchronization.
Pthread (continue) General pthread program structure –Encapsulate parallel parts (can be almost the whole program) in functions. –Use function arguments.
Semaphores. Readings r Silbershatz: Chapter 6 Mutual Exclusion in Critical Sections.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
2-1 The critical section –A piece of code which cannot be interrupted during execution Cases of critical sections –Modifying a block of memory shared by.
CSE451 NT Synchronization Autumn 2002 Gary Kimura Lecture #9 October 18, 2002.
Mutual Exclusion. Readings r Silbershatz: Chapter 6.
1 Announcements The fixing the bug part of Lab 4’s assignment 2 is now considered extra credit. Comments for the code should be on the parts you wrote.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
® 7-2 Semaphores 7.1Overview Binary Semaphores and Synchronization Mutual Exclusion.
Kernel Locking Techniques by Robert Love presented by Scott Price.
Lecture 8 Page 1 CS 111 Online Other Important Synchronization Primitives Semaphores Mutexes Monitors.
Overview Task State Diagram Task Priority Idle Hook AND Co-Routines
Chapter 6 – Process Synchronisation (Pgs 225 – 267)
ECGR-6185 µC/OS II Nayana Rao University of North Carolina at Charlotte.
2.3 interprocess communcation (IPC) (especially via shared memory & controlling access to it)
CS 3204 Operating Systems Godmar Back Lecture 7. 12/12/2015CS 3204 Fall Announcements Project 1 due on Sep 29, 11:59pm Reading: –Read carefully.
1 VxWorks 5.4 Group A3: Wafa’ Jaffal Kathryn Bean.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
 Wind River Systems, Inc Chapter - 7 Intertask Communication.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles Synchronization Emery Berger and Mark Corner University.
Concurrency in Shared Memory Systems Synchronization and Mutual Exclusion.
CS333 Intro to Operating Systems Jonathan Walpole.
Synchronization CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han.
CSCI1600: Embedded and Real Time Software Lecture 17: Concurrent Programming Steven Reiss, Fall 2015.
1 5-High-Performance Embedded Systems using Concurrent Process (cont.)
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition Chapter 6: Process Synchronization.
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
Embedded Real-Time Systems Processing interrupts Lecturer Department University.
Chapter 7: Semaphore Management Seulki Lee 1. Semaphore?  A protocol mechanism offered by most multitasking kernels  Control access to a shared resource.
Transmitter Interrupts Review of Receiver Interrupts How to Handle Transmitter Interrupts? Critical Regions Text: Tanenbaum
Lecture 8 Task Utilization. Theoretical Analysis.
Topics Covered What is Real Time Operating System (RTOS)
CS703 – Advanced Operating Systems
Chapter 5: Process Synchronization – Part 3
Chapter 5: Process Synchronization – Part II
Outline Other synchronization primitives
Other Important Synchronization Primitives
An Embedded Software Primer
Transmitter Interrupts
Lecture 2 Part 2 Process Synchronization
CSCI1600: Embedded and Real Time Software
CSE 153 Design of Operating Systems Winter 19
CSE 153 Design of Operating Systems Winter 2019
CS333 Intro to Operating Systems
Intertask Communication
CSCI1600: Embedded and Real Time Software
Akos Ledeczi EECE 6354, Fall 2017 Vanderbilt University
Akos Ledeczi EECE 6354, Fall 2015 Vanderbilt University
Presentation transcript:

 Wind River Systems, Inc Chapter - 6 Semaphores

6-2 Semaphores Overview Binary Semaphores and Synchronization Mutual Exclusion

6-3 Overview Three semaphore types available: A semaphore is a kernel primitive object. Semaphore operations : Can change a task’s state. Are fast. Binary semaphores allow a task to pend until a given event occurs (e.g., an interrupt). Mutual exclusion semaphores allow a task to acquire an exclusive lock to a shared resource (e.g., a file or a device). Counting semaphores are available: Less commonly used. See manual pages for details.

6-4 Semaphores Overview Binary Semaphores and Synchronization Mutual Exclusion

6-5 The synchronization Problem Task myGetData () { requestData (); waitForData (); getData (); } Task may need to wait for an event to occur. Busy waiting (i.e., polling) is inefficient. Pending until the event occurs is better.

6-6 The Synchronization Solution Create a binary semaphore for the event. Full (event has occurred). Binary semaphores exist in one of two states: Empty (event has not occurred). Task waiting for the event calls semTake(), and blocks until semaphore is given. Task or interrupt service routine detecting the event calls semGive(), which unblocks the waiting task.

6-7 Binary Semaphores SEM_ID semBCreate (options, intialState) optionsSepcify queue type (SEM_Q_PRIORITY or SEM_Q_FIFO) for tasks pended on this semaphore. initialStateInitialize semaphore to be available (SEM_FULL) or unavailable (SEM_EMPTY). Semaphores used for synchronization are typically initialized to SEM_EMPTY (event has not occurred). Returns a SEM_ID, or NULL on error.

6-8 Taking a Semaphore STATUS semTake (semId, timeout) semIdThe SEM_ID returned from semBCreate(). timeoutMaximum time to wait for semaphore. Value can be clock ticks, WAIT_FOREVER, or NO_WAIT. Can pend the task until either Semaphore left unavailable. Semaphore is given or Timeout expires. Returns OK if successful, ERROR on timeout (or invalid semId).

6-9 Taking a Binary Semaphore semaphore available ? task pends until sem is given or timeout timeout task unpends semTake() returns ERROR no task continues semTake() returns OK Yes task unpends, semTake() returns OK Semaphore given

6-10 Giving a Semaphores STATUS semGive (semId) Unblocks a task waiting for semId. If no task is waiting, make semId available. Returns OK, or ERROR if semId is invalid.

6-11 Giving a Binary Semaphore tasks pended ? semaphore made available no task at front of queue made ready semaphore remains unavailable yes

6-12 Information Leakage Fast event occurrences can cause lost information. Suppose a VxWorks task (priority=100) is executing the following code, with semId initially unavailable: FOREVER { semTake (semId, WAIT_FOREVER); printf (“Got the semaphore\n”); } What would happen in the scenarios below ? 1.-> repeat (1, semGive, semId); 2.-> repeat (2, semGive, semId); 3.-> repeat (3, semGive, semId);

6-13 Synchronizing Multiple Tasks STATUS semFlush (semId) Unblocks all tasks waiting for semaphore. Does not affect the state of a semaphore. Useful for synchronizing actions of multiple tasks.

6-14 Semaphores Overview Binary Semaphores and Synchronization Mutual Exclusion

6-15 Mutual Exclusion Problem Some resources may be left inconsistently if accessed by more than one task simultaneously. Must obtain exclusive access to such a resource before using it. We say a race condition exists. Mutual exclusion cannot be compromised by priority. Shared data structures. Shared files. Shared hardware devices. Very difficult to detect during testing. If exclusive access is not obtained, then the order in which tasks execute affects correctness.

6-16 Race Condition Example tTask1tTask2 1char myBuf(BU_SIZE);/* store data here */ 2int myBufIndex = -1;/* Index of last data */ 3 4myBufPut (char ch) 5{ 6myBufIndex++; 7myBuf [myBufIndex] = ch; 8} myBufIndex++ myBuf [myBufIndex] = ‘b’ myBuf [myBufIndex] = ‘a’ …….

6-17 Solution Overview Create a mutual exclusion semaphore to guard the resource. Call semTake() before accessing the resource; call semGive() when done. semTake() will block until the semaphore (and hence the resource) becomes available. semGive() releases the semaphore (and hence access to the resource).

6-18 Creating Mutual Exclusion Semaphores SEM_ID semMCreate (options) options can be : queue specificationSEM_Q_FIFO or SEM_Q_PRIORITY deletion safetySEM_DELETE_SAFE priority inheritanceSEM_INVERSION_SAFE Initial state of semaphore is available.

6-19 Mutex Ownership A task which takes a mutex semaphore “owns” it, so that no other task can give this semaphore. Mutex semaphores can be taken recursively. The task which owns the semaphore may take it more than once. Must be given same number of times as taken before it will be released. Mutual exclusion semaphores cannot be used in an interrupt service routine.

6-20 Taking a Mutex Semaphore owner of semaphore task pends until sem is given or timeout another task task continues semTake() returns OK Task becomes owner no one task continues semTake() returns OK task ownership count incremented this task

6-21 Giving a Mutex Semaphore ownership count? semaphore made available one semGive() returns ERROR not owner Greater than one tasks pended? no decrement ownership count task at head of queue is made ready, becomes owner yes

6-22 Code Example - Solution 1 #include ”vxWorks.h” 2 #include ” semLib.h” 3 4 LOCAL char myBuf[BUF_SIZE]; /* Store data here */ 5 LOCAL int myBufIndex = -1; /* Index of last data */ 6 LOCAL SEM_ID mySemId; 7 8 void myBufInit ( ) 9 { 10mySemID = semNCreate SEM_Q_PRIORITY | 11SEM_INVERSION_SAFE | 12SEM_DELETE_SAFE ); 13} void myBufPut (char ch) 16 { 17semTake(mySemId, WAIT_OREVER); 18myBufIndex++; 19myBuf[myBufIndex] = ch; 20semGIve (mySemId); 21}

6-23 Deletion Safety Deleting a task which owns a semaphore can be catastrophic. data structures left inconsistent. semaphore left permanently unavailable. The deletion safety option prevents a task from being deleted while it owns the semaphore. Enabled for mutex semaphores by specifying the SEM_DELETE_SAFE option during semMCreate( ).

6-24 Priority Inversion High Priority Medium Priority Low Priority Pended tHigh unblocks tMediumu nblocks semTake( ) Pended Ready semTake( ) Critical Region Ready time

6-25 Priority Inheritance Priority inheritance algorithm solves priority inversion problem. Task owning a mutex semaphore is elevated to priority of highest priority task waiting for that semaphore. Enabled on mutex semaphore by specifying the SEM_INVERSION_SAFE option during semMCreat( ). Must also specify SEM_Q_PRIORITY (SEM_Q_FIFO is incompatible with SEM_INVERSION_SAFE).

6-26 Priority Inversion Safety High Priority Medium Priority Low Priority Pended tHigh unblocks tMediumu nblocks semTake( ) Pended Pend Ready semTake( ) Critical Region Ready Time semGive( )

6-27 Avoiding Mistakes It is easy to miuse mutex semaphores, since you must protect all accesses to the resource. To prevent such a mistake Write a library of routines to access the resource. Initialization routine creates the semaphore. Routines in this library obtain exclusive access by calling semGIve( ) and semTake( ). All uses of the resource are through this library.

6-28 Caveat - Deadlocks A deadlock is a race condition associated with the taking of multiple mutex semaphores. Very difficult to detect during testing. INT 6 INT 3 tExcTask tLogTask tEvtTask tWdbTask tNetTask tTaskHi tTaskLow tPortmapd tWvSvc u0 idle semTake(semId1,-1) semTake(semId2,-1)

6-29 Other Caveats Mutual exclusion semaphores can not be used at interrupt time. This issue will be discussed later in the chapter. Keep the critical region (code between semTake( ) and semGive( )) short.

6-30 Common Routines Additional semaphore routines : semDelete( )Destroy the semaphore.semTake( ) calls for all tasks pended on the semaphore return ERROR. show( )Display semaphore information.

6-31 Semaphore Browser To inspect the properties of a specific semaphore insert the semaphore ID in the Browser’s Show box, and click on Show. Attributes Blocked Tasks

6-32 Locking out Preemption When doing something quick frequently, it is preferable to lock the scheduler instead of using a Mutex semaphore. Call taskLock( ) to disable scheduler. Call taskUnLock( ) to reenable scheduler. Does not disable interrupts. If the task blocks, the scheduler is reenabled. Prevents all other tasks from running, not just the tasks contending for the resource.

6-33 ISR’s and Mutual Exclusion ISR’s can’t use Mutex semaphores. Task sharing a resource with an ISR may need to disable interrupts. To disable / re-enable interrupts : int intLock( ) voidintUnLock(lockKey) lockKey is return value from intLock( ). Keep interrupt lock-out time short (e.g., long enough to set a flag) ! Does not disable scheduler.

6-34 Summary BinaryMutual Exclusion semBCreatesemMCreate semDelete semTake, semGive show

6-35 Binary semaphores allow tasks to pend until some event occurs. Create a binary semaphore for the given event. Tasks waiting for the event blocks on a semTake( ). Task or ISR detecting the event calls semGive( ) or semFlush( ). Caveat : if the event repeats too quickly, information may be lost Summary

6-36 Mutual Exclusion Semaphores are appropriate for obtaining access to a resource. Create a mutual exclusion semaphore to guard the resource. Mutex semaphores have owners. Caveats : Before accessing the resource, call semTake( ). To release the resource, call semGive( ). Keep critical regions short. Make all accesses to the resource through a library of routines. Can’t be used at interrupt time. Deadlocks. Summary

6-37 taskLock( ) / taskUnLock( ) : Prevents other tasks from running. Use when doing something quick frequently. Caveat : keep critical region short. intLock( ) / intUnLock( ) : Disable interrupts. Use to protect resources used by tasks and interrupt service routines. Caveat : keep critical region short. Summary