Embedded RealTime Systems Lecture Synchronization Real Time Systems

Embedded Real-Time Systems Lecture: Synchronization – Real Time Systems Dimitris Metafas, Ph. D.

1. Synchronization

Synchronization Semaphores n n Semaphore an integer variable (> 0) that normally can take on only non zero values Only three operations can be performed on a semaphore all operations are atomic n init(s, #) n n wait(s) or P(s) n n n sets semaphore, s, to an initial value # if s > 0, then s = s 1; else suspend the process that called wait signal(s) or V(s) n n s = s + 1; if some process P has been suspended by a previous wait(s), wake up process P n normally, the process waiting the longest gets woken up 3

Types of Synchronization with Semaphores n n n There are 2 basic types of synchronization n Mutex – where semaphores serve to protect a critical section (shared data/code) n Barrier synchronization – where semaphores are used sort of as an inter task communication facility to “wake up” other waiting processes Remember P=wait and V=signal Here, s 1 and s 2 are semaphores P 1 P(s 1). . . V(s 1) P 2 P(s 1). . . V(s 1) P 1 P(s 1). . . V(s 2) Mutex P 2 P(s 2). . . V(s 1) Barrier Synchronization Initial value of s 1 = 1, s 2 = 0 4

Producer – Consumer problem n One process produces data, the other consumes it producer(){ while(1){ produce(); append. To. Buffer(); signal(item. Ready); } } consumer(){ while(1){ wait(item. Ready); take. From. Buffer(); consume(); } } Initially, item. Ready = 0; 5

Producer – Consumer (2) n What if both append. To. Buffer and take. From. Buffer cannot overlap in execution? n For example, if buffer is a shared link list between producer and consumer? n Or, multiple producers and consumers producer() { while(1){ produce(); wait(mutex); append. To. Buffer(); signal(mutex); signal(item. Ready); } } n consumer() { while(1){ wait(item. Ready); wait(mutex); take. From. Buffer(); signal(mutex); consume(); } } Initially, mutex = 1, item. Ready = 0; 6

Producer – Consumer (3) n Assume a single buffer of fixed size n n n Consumer blocks (sleeps) when buffer is empty Producer blocks (sleeps) when the buffer is full producer() { consumer() { while(1){ produce(); wait(item. Ready); wait(spaces. Left); wait(mutex); take. From. Buffer(); append. To. Buffer(); signal(mutex); signal(spaces. Left); signal(item. Ready); consume(); } } Initially, mutex = 1, item. Ready = 0; spaces. Left = size. Of. Buffer; 7

Example n You can assume that both processes get scheduled to run in some order (you cannot assume the order in which the processes will run). Variables x, y, q and s are initialized as follows: x = 5, y = 3, q=1, s=1. List all possibile values of x and y. . Process 1 BEGIN x = x − 3; END Process 2 BEGIN x = x − 3; END Possible values of (x, y) are (-1, 3) and (2, 3) 8

Example n You can assume that both processes get scheduled to run in some order (you cannot assume the order in which the processes will run). Variables x, y, q and s are initialized as follows: x = 5, y = 3, q=1, s=1. List all possibile values of x and y. Process 1 BEGIN x = y − 1; y=y+1 END Process 2 BEGIN x = y − 1; y=y+1 END Possible values of (x, y) are (2, 4), (2, 5), (3, 5) 9

Example n You can assume that both processes get scheduled to run in some order (you cannot assume the order in which the processes will run). Variables x, y, q and s are initialized as follows: x = 5, y = 3, q=1, s=1. List all possibile values of x and y. Process 1 BEGIN P( s ) x = y − 1; V( s ) P( q ) y = y +1 V( q ) END Process 2 BEGIN P( s ) x = y − 1; V( s ) P( q ) y=y+1 V( q ) END Possible values of (x, y) are (2, 5) and (3, 5) 10

Example n You can assume that both processes get scheduled to run in some order (you cannot assume the order in which the processes will run). Variables x, y, q and s are initialized as follows: x = 5, y = 3, q=1, s=1. List all possibile values of x and y. Process 1 BEGIN P( s ) x = x − 3; y=y+1 V( s ) END Process 2 BEGIN P( s ) x = x − 3; y=y+1 V( s ) END Possible values of (x, y) are (-1, 5) 11

Deadlocks n When a program is written carelessly, it may cause a deadlock P 1: : P(s 1); P(s 2); . . . V(s 2); V(s 1); P 2: : P(s 2); P(s 1); . . . V(s 1); V(s 2); 12

Deadlocks (2) n n Several processes “executing” at the same time, and one is waiting (blocked) for (by) another, which in turn is waiting for another, which in turn. . . which in turn is waiting for the first. n No process can finish, since they are all waiting for something The difference between deadlock and starvation of a process is that n In deadlock, a process must be able to acquire a resource at first, and then go into deadlock. n In starvation, the request may be deferred infinitely n n the resource may be in use for an infinite amount of time Livelock is similar to deadlock n But in livelock the state of the process can change constantly with regards to the other process but no progress is made n Example: two people walking towards each other in a corridor, both step aside to let the other person pass but both step aside in the same direction. . . 13

Resources n n n What could be a resource? n Hardware devices e. g. printer, tape drive needed by a process to do useful work n Software resource e. g. mutex Processes utilize resources in the following sequence n Request (must wait if request is not granted) n Use n Release How do we get into a deadlock n Consider a system with one printer and one tape drive n Process 1 requests printer and the request is granted n Process 2 requests tape drive and the request is granted n Process 1 also needs tape drive to finish its job n n Process 2 also needs printer to finish its job n n Must wait for Process 2 to release tape drive Must wait for Process 1 to release tape drive Deadlock! 14

Conditions for Deadlock n Formally: (all of these conditions must hold for deadlock to occur) n Mutual exclusion: some resource is non sharable , (eg, a printer) n Hold and wait: there must exist a process holding for a resource (eg, a printer) and waiting for another resource (eg, a plotter) n No preemption: the system will not preempt the resources in contention n Circular wait: there must exist a circular chain of processes. n One is holding a resource and waiting for the next process 15

Deadlock Handling n n n Prevention: structure the system is such a way as to avoid deadlocks (i. e. , in a way to avoid one of the conditions above). n This is done in the design phase: design a system and ensure that there is no deadlock in the system Avoidance: does not make deadlock impossible (as in prevention) n Instead, it rejects requests that cause deadlocks by examining the requests before granting the resources. If there will be a deadlock, reject the request Detection and Recovery: after the deadlock has been detected, break one of the 4 conditions above. The mechanisms of deadlock detection and deadlock recovery are very much tied to each other 16

2. Real Time Systems

Real Time Systems n n Real time systems: correctness of the system depends not only upon the logical correctness of the output but also upon the time at which the results are delivered n Subject to both temporal and logical constraints n Example: Not enough to say that “brakes were applied”, a real time system should say “brakes were applied at correct time” Examples of real time systems n Transportation: automobiles, railways, subways, aircraft, ships, elevators n Traffic control: airspace, highways, shipping n Medical: pacemakers, radiation, patient monitoring n Military: command control, missile defense, radar tracking n Manufacturing: automated plants 18

Example n Example: A simple one sensor, one actuator control system n n n reference input r(t) set timer to interrupt periodically with period T (sampling period); at each timer interrupt do do analog to digital conversion to get y; compute control output u; output u and do digital to analog conversion; end do A/D rk yk control law uk D/A computation y(t) sensor u(t) plant actuator The system being controlled 19

Other example n n n Digital Set top box: receives compressed (MPEG 2) video and audio data (bits) for each frame Frame rate is 30 frames/sec (i. e. 30 frames are displayed on the TV screen per second) Each frame has to be decoded within 1/30 = 33 ms to ensure that video data is available when the frame needs to be displayed n Audio data needs to be processed too, and decryption (if any) needs to be done during this time frame 20

Real Time n n What does real time mean? n A real time service is one that is required to be delivered within time intervals dictated by the environment n Temporal constraints are a part of the results’ correctness criteria What makes a real time system different? n Timing constraints n Must satisfy timing constraints involving relative and absolute times n n Concurrency n Must deal with the natural concurrency of the physical world n n Example: a deadline is a limit on the amount of time for completing an operation or a computation Example: Sensors can fire simultaneously “Real time” does not mean “fast” n Real time = meeting timing constraints n Fast = doing something quickly 21

Terminology n n n Job: Instance of a task Release time of a job: The time instant the job becomes ready to execute Absolute Deadline of a job: The time instant by which the job must complete execution Relative deadline of a job: “Deadline Release time” Response time of a job: “Completion time Release time” 22

Example 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 = job release = job deadline Job Its Its is released at time 3. (absolute) deadline is at time 10. relative deadline is 7. response time is 6. 23

Hard/Soft Real Time n A hard deadline must be met n If any hard deadline is ever missed, then the system is incorrect n Requires a means for validating that deadlines are met Hard real-time system: A real time system in which at least one deadline is hard Examples: Automotive braking systems, flight control, … n A soft deadline may occasionally be missed n n Soft real-time system: A real time system in which all deadlines are soft Examples: Multimedia Systems 24

Kind of Real Time Tasks n Periodic processes/tasks n n n Time driven Activated on a regular basis between fixed time intervals Specified by {Ci , Ti , Di, } n n n Ti = period of task ti Di = deadline (relative) for task ti Example: periodic monitoring or sampling of sensors Sporadic processes/tasks n n Ci = worst case compute time (execution time) for task ti Event driven Activated by an external entity or an environmental change Example: Events such as faults Aperiodic processes/tasks n n n Event driven Multiple simultaneously or closely arriving events For bursty events or bursty actions 25

Metrics for real time systems differ from that for time sharing systems. Time-Sharing Systems Real-Time Systems Capacity High throughput Schedulability Responsiveness Fast average response Ensured worst case response Overload Fairness Stability n n n Schedulability is the ability of tasks to meet all hard deadlines Latency is the worst case system response time to events Stability in overload means the system meets critical deadlines even if all deadlines cannot be met 26

Why are deadlines missed ? n n n For a given task, consider n Preemption: time waiting for higher priority tasks n Execution: time to do its own work n Blocking: time delayed by lower priority tasks The task is schedulable if the sum of its preemption, execution, and blocking is less than its deadline. Focus: identify the biggest hits among the three and reduce, as needed, for schedulability 27

Jitter / Drift n A periodic task should repeat regularly according to a given period. n For example, a periodic task with period 10 starting at t = 0 28

Classification of the scheduling algorithms All scheduling algorithms priority scheduling (priority driven) no priority scheduling (clock driven) fixed priority scheduling 29 dynamic priority scheduling

Scheduling Algorithms (No Priority) n n n Non priority based n All tasks are created equal n There is no way to indicate which tasks are more “important” (more critical) than others First In First Out (FIFO) or First Come First Served (FCFS) n Ready tasks are inserted into a list n Tasks are dispatched from the list in their order of entry in the list n No preemption, i. e. , a task runs to completion before the next task runs n No consideration of task priorities Round Robin Preemptive n Ready tasks are dispatched in turn n Each task given its fair share of fixed execution time n Preemption of running task at the end of the fixed interval n No consideration of task priorities 30

Scheduling Algorithms (Fixed Priority) n n n Fixed priority based n All tasks are not created equal n Some tasks have more importance (higher priority) than others n Once a task’s priority is assigned, it cannot change during run time Rate Monotonic Analysis (RMA) n Shorter the period, the higher the priority of the task n Assigns fixed priorities in reverse order of period length n Tasks requiring frequent attention have higher priority and get scheduled earlier Least Compute Time (LCT) n Shorter the computation time, the higher the priority of the task n Assigns fixed priorities in reverse order of computation length n Tasks finishing quickly have higher priority and get scheduled earlier 31

Scheduling Algorithms (Dynamic Priority) n n Dynamic priority based n All tasks are not created equal n Some tasks have more importance (higher priority) than others n Task’s priority (and thus, the schedule) may change during execution Shortest Completion Time (SCT) n Ready task with the smallest remaining compute time gets scheduled first Earliest Deadline First (EDF) n Ready task with the earliest future deadline gets scheduled first Least Slack Time (LST) n Ready task with the smallest amount of free/slack time within the cycle gets scheduled first 32

Real Time Scheduling n n A set of tasks is schedulable if all tasks are guaranteed to meet their deadlines Why will a set of tasks be not schedulable? n Priority assignment n The values of C and Ts for the tasks (their utilization factor) Example – T 1 (1, 2) & T 2 (2, 5) are two tasks. Two cases arise depending T 1 misses deadline on which task is assigned higher priority 0 1 2 3 4 5 0 t 1 t 2 T 1 has higher priority 1 2 3 4 5 T 2 has higher priority 33
- Slides: 33