10/09/2007ecs150 Fall 20071 Operating System ecs150 Fall 2007 : Operating System #2: Scheduling and...

Post on 19-Dec-2015

215 views 0 download

Tags:

Transcript of 10/09/2007ecs150 Fall 20071 Operating System ecs150 Fall 2007 : Operating System #2: Scheduling and...

10/09/2007 ecs150 Fall 2007 1

ecs150 Fall 2007:Operating SystemOperating System#2: Scheduling and Mutual Exclusion(chapter 4)

Dr. S. Felix Wu

Computer Science Department

University of California, Davishttp://www.cs.ucdavis.edu/~wu/

sfelixwu@gmail.com

10/09/2007 ecs150 Fall 2007 2

Kernel and User SpaceKernel and User Space

Process FOOFOOMemoryspace for thisprocess

System call(or trap into the kernel)

program

System Call

conceptually

Kernel Resources(disk or IO devices)

Process FOOFOOin the Kernel

10/09/2007 ecs150 Fall 2007 3

States of a ProcessStates of a Process

Running, Blocked, and Ready

Running

Waiting Ready

10/09/2007 ecs150 Fall 2007 4

Running

Blocked Ready

Running

Blocked Ready

Running

Blocked Ready

Running

Blocked Ready

Scheduling &Context Switching

10/09/2007 ecs150 Fall 2007 5

Basic ConceptsBasic Concepts

Maximum CPU utilization obtained with multiprogramming

CPU–I/O Burst Cycle – Process execution consists of a cycle of CPU execution and I/O wait.

CPU burst distribution Processes classified as CPU bound or I/O

bound

10/09/2007 ecs150 Fall 2007 6

CPU SchedulerCPU Scheduler Selects from among the processes in memory that

are ready to execute, and allocates the CPU to one of them.

CPU scheduling decisions may take place when a process:

1.Switches from running to waiting state.

2.Switches from running to ready state.

3.Switches from waiting to ready.

4.Terminates. Scheduling under 1 and 4 is nonpreemptive. All other scheduling is preemptive.

10/09/2007 ecs150 Fall 2007 7

Preemptive vs.Preemptive vs.NonpreemptiveNonpreemptive

Preemptive:

Nonpreemptive:

Pros and Cons…..

10/09/2007 ecs150 Fall 2007 8

User P Kernel Process Kernel P Kernel Process

10/09/2007 ecs150 Fall 2007 9

Context SwitchingContext Switching

10/09/2007 ecs150 Fall 2007 10

DispatcherDispatcher

Dispatcher module gives control of the CPU to the process selected by the short-term scheduler; this involves:– switching context– switching to user mode– jumping to the proper location in the user

program to restart that program Dispatch latency – time it takes for the dispatcher

to stop one process and start another running.

10/09/2007 ecs150 Fall 2007 11

Preemptive SchedulingPreemptive Scheduling

fixed time window timer/clock interrupt– scheduling decision– “bill” the process– context switching might or might not happen

Priority Fairness …

10/09/2007 ecs150 Fall 2007 12

Example: two schedulesExample: two schedules

100 msec slotwith around 5 mseccontext switchingoverhead….

Which one is better?And Why?

10/09/2007 ecs150 Fall 2007 13

Optimization CriteriaOptimization Criteria

Max CPU utilization Max throughput Min turnaround time Min waiting time Min response time

– but obviously, we have some trade-off…

10/09/2007 ecs150 Fall 2007 14

First-Come, First-Served (FCFS)First-Come, First-Served (FCFS)

Process Burst Time

P1 24

P2 3

P3 3

Suppose that the processes arrive in the order: P1 , P2 , P3

The Gantt Chart for the schedule is:

Waiting time for P1 = 0; P2 = 24; P3 = 27

Average waiting time: (0 + 24 + 27)/3 = 17

P1 P2 P3

24 27 300

10/09/2007 ecs150 Fall 2007 15

Example 1Example 1

10/09/2007 ecs150 Fall 2007 16

Shortest-Job-First (SJF)Shortest-Job-First (SJF) Associate with each process the length of its next CPU burst.

Use these lengths to schedule the process with the shortest time. Two schemes:

– nonpreemptive – once CPU given to the process it cannot be preempted until completes its CPU burst.

– preemptive – if a new process arrives with CPU burst length less than remaining time of current executing process, preempt. This scheme is know as the Shortest-Remaining-Time-First (SRTF).

SJF is optimal – gives minimum average waiting time for a given set of processes.

10/09/2007 ecs150 Fall 2007 17

Process Arrival Time Burst Time

P1 0.0 7

P2 2.0 4

P3 4.0 1

P4 5.0 4

SJF (non-preemptive)

Average waiting time = (0 + 6 + 3 + 7)/4 - 4

ExampleExample

P1 P3 P2

73 160

P4

8 12

10/09/2007 ecs150 Fall 2007 18

Issues for SJFIssues for SJF

???

10/09/2007 ecs150 Fall 2007 19

CPU BurstsCPU Bursts

CPU–I/O Burst Cycle – Process execution consists of a cycle of CPU execution and I/O wait.

CPU burst distribution Processes classified as CPU bound or

I/O bound

10/09/2007 ecs150 Fall 2007 20

Determining Length of Next CPU Determining Length of Next CPU BurstBurst

Can only estimate the length. Can be done by using the length of previous CPU

bursts, using exponential averaging.

:Define 4.

10 , 3.

burst CPU next the for value predicted 2.

burst CPU of lenght actual 1.

≤≤=

=

+

αατ 1n

thn nt

( ) .1 1 nnn t ταατ −+=+

10/09/2007 ecs150 Fall 2007 21

10/09/2007 ecs150 Fall 2007 22

Priority SchedulingPriority Scheduling A priority number (integer) is associated with each

process The CPU is allocated to the process with the highest

priority (smallest integer highest priority).

– Preemptive

– Non-preemptive

SJF is a priority scheduling where priority is the predicted next CPU burst time.

FCFS is a priority scheduling where priority is the arrival time.

10/09/2007 ecs150 Fall 2007 23

““Fixed” PriorityFixed” Priority

What is it?– The process sticks with the origin assigned priority.

A good or bad idea? What other possible policy?

– Dynamic policy. Problem Starvation – low priority processes may never

execute. Solution Aging – as time progresses increase the priority of

the process.

– Hybrid policy.

10/09/2007 ecs150 Fall 2007 24

Round Robin (RR)Round Robin (RR) Each process gets a small unit of CPU time (time

quantum), usually 10-100 milliseconds. After this time has elapsed, the process is preempted and added to the end of the ready queue.

If there are n processes in the ready queue and the time quantum is q, then each process gets 1/n of the CPU time in chunks of at most q time units at once. No process waits more than (n-1)q time units.

Performance

– q large FIFO

– q small q must be large with respect to context switch, otherwise overhead is too high.

10/09/2007 ecs150 Fall 2007 25

Process Burst Time

P1 53

P2 17

P3 68

P4 24

The Gantt chart is:

Typically, higher average turnaround than SJF, but better response.

P1 P2 P3 P4 P1 P3 P4 P1 P3 P3

0 20 37 57 77 97 117 121 134 154 162

10/09/2007 ecs150 Fall 2007 26

I/O system calls

1

2

3

10/09/2007 ecs150 Fall 2007 27

Past CPU UsagePast CPU Usage

Round-Robin How many CPU cycles so far

– fairness How about #3?

10/09/2007 ecs150 Fall 2007 28

Past CPU UsagePast CPU Usage

Round-Robin How many CPU cycles so far

– fairness How many CPU cycles you have used

lately– aging factor: 4 cycles

10/09/2007 ecs150 Fall 2007 29

BSD SchedulingBSD Scheduling

For each tick (10 msec):– Pi

estcpu = Piestcpu + Tick(Pi)

For each decaying period (1 second):– Pi

estcpu = Piestcpu*(2*load)/(2*load+1)+Pi

nice load: # of processes in the ready queue

Example: 1 process in the queue– Pi

estcpu = Piestcpu*0.66 + Pi

nice

– in 4 seconds, (0.66)4 = 0.001296

10/09/2007 ecs150 Fall 2007 30

LinuxLinux

Linux provides two process scheduling algorithms– Time sharing for fairness

– Real-time, where priorities are more important than fairness

Linux allows only user-mode processes to be preempted– kernel mode processes may not be interrupted

Formula – a balance between software real-time and fairness

– Picredit = Pi

credit / 2 + Priorityi

10/09/2007 ecs150 Fall 2007 31

SchedulingScheduling

Fairness: Round-Robin Responsiveness: SJF Utilization: Aging, promoting System Calls. Fairness in Inter-process communication

10/09/2007 ecs150 Fall 2007 32

BSD SchedulingBSD Scheduling

For each tick (10 msec):– Pi

estcpu = Piestcpu + Tick(Pi)

For each decaying period (1 second):– Pi

estcpu = Piestcpu*(2*load)/(2*load+1)+Pi

nice load: # of processes in the ready queue

Example: 1 process in the queue– Pi

estcpu = Piestcpu*0.66 + Pi

nice

– in 4 seconds, (0.66)4 = 0.001296

10/09/2007 ecs150 Fall 2007 33

Load = 1Load = 1

2Load/(2Load+1) ~ 0.66 Pi

estcpu = Piestcpu*(0.66)1 – 20

Piestcpu = Pi

estcpu*(0.66)2 – 20

Piestcpu = Pi

estcpu*(0.66)3 – 20

Piestcpu = Pi

estcpu*(0.66)4 – 20

– (0.66)4 = 0.001296

10/09/2007 ecs150 Fall 2007 34

Load = 50Load = 50

2Load/(2Load+1) ~ 0.99 Pi

estcpu = Piestcpu*(0.99)1 – 20

Piestcpu = Pi

estcpu*(0.99)2 – 20

Piestcpu = Pi

estcpu*(0.99)3 – 20

Piestcpu = Pi

estcpu*(0.99)4 – 20

– (0.99)4 = 0.9606

10/09/2007 ecs150 Fall 2007 35

1

0

0

1

0

1

::.

256 different priorities64 scheduling classes

RR

10/09/2007 ecs150 Fall 2007 36

1

0

0

1

0

1

::. 256 different priorities

64 scheduling classes

RR

0~63 bottom-half kernel (interrupt)64~127 top-half kernel128~159 real-time user160~223 timeshare224~255 idle

kg_estcpu

10/09/2007 ecs150 Fall 2007 37

10/09/2007 ecs150 Fall 2007 38

static voidschedcpu(void *arg){ ... FOREACH_PROC_IN_SYSTEM(p) { FOREACH_KSEGRP_IN_PROC(p, kg) { awake = 0; FOREACH_KSE_IN_GROUP(kg, ke) { ... } /* end of kse loop */

kg->kg_estcpu = decay_cpu(loadfac, kg->kg_estcpu); resetpriority(kg); FOREACH_THREAD_IN_GROUP(kg, td) { if (td->td_priority >= PUSER) { sched_prio(td, kg->kg_user_pri); } } } /* end of ksegrp loop */ } /* end of process loop */}

/usr/src/sys/kern/sched_4bsd.c

10/09/2007 ecs150 Fall 2007 39

static voidresetpriority(struct ksegrp *kg){ register unsigned int newpriority; struct thread *td;

if (kg->kg_pri_class == PRI_TIMESHARE) { newpriority = PUSER + kg->kg_estcpu / INVERSE_ESTCPU_WEIGHT + NICE_WEIGHT * (kg->kg_nice - PRIO_MIN); newpriority = min(max(newpriority, PRI_MIN_TIMESHARE), PRI_MAX_TIMESHARE); kg->kg_user_pri = newpriority; }

FOREACH_THREAD_IN_GROUP(kg, td) { maybe_resched(td); /* XXXKSE silly */ }}

/usr/src/sys/kern/sched_4bsd.c

10/09/2007 ecs150 Fall 2007 40

struct kse *sched_choose(void){

struct kse *ke;

ke = runq_choose(&runq);

if (ke != NULL) {runq_remove(&runq, ke);ke->ke_state = KES_THREAD;

KASSERT((ke->ke_thread != NULL), ("runq_choose: No thread on KSE"));KASSERT((ke->ke_thread->td_kse != NULL), ("runq_choose: No KSE on thread"));KASSERT(ke->ke_proc->p_sflag & PS_INMEM, ("runq_choose: process swapped out"));

}return (ke);

}

/usr/src/sys/kern/sched_4bsd.c

10/09/2007 ecs150 Fall 2007 41

#define loadfactor(loadav) (2 * (loadav))#define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))

static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; #define CCPU_SHIFT 11

/usr/src/sys/kern/sched_4bsd.c

10/09/2007 ecs150 Fall 2007 42

/* * Compute a tenex style load average of a quantity on * 1, 5 and 15 minute intervals. * XXXKSE Needs complete rewrite when correct info is * available. * Completely Bogus.. * only works with 1:1 (but compiles ok now :-) */static voidloadav(void *arg){

}

/usr/src/sys/kern/kern_synch.c

10/09/2007 ecs150 Fall 2007 43

Lottery SchedulingLottery Scheduling(a dollar and a dream)(a dollar and a dream)

A process P(I) has L(I) lottery tickets. Totally, we have N tickets among all processes. P(I) has L(I)/N probability to get CPU cycles. Difference between Priority and Tickets:

– Priority: which process is more important? The importance is “infinitely” big!!

– Tickets: how much more important? Quantify the importance.

10/09/2007 ecs150 Fall 2007 44

J, Pri(J) = 1 I, Pri(I) = 120

J,80% I J I

I J J J I J J J J J J J I J J J J I J J

10/09/2007 ecs150 Fall 2007 45

Lottery SchedulingLottery Scheduling

At each scheduling decision point:– Ticket assignment:

For each ticket in each process, produce a unique random number (we can not have more than one process sharing the prize).

– Ticket drawing: Produce another random number until a winner is

identified.

10/09/2007 ecs150 Fall 2007 46

Efficient ImplementationEfficient Implementation

Maybe only the # of tickets matters…

One rand( ) could produce 32 random bits.

0-16

10/09/2007 ecs150 Fall 2007 47

ExampleExample422

10/09/2007 ecs150 Fall 2007 48

static voidschedcpu(void *arg){ ... FOREACH_PROC_IN_SYSTEM(p) { mtx_lock_spin(&sched_lock); FOREACH_KSEGRP_IN_PROC(p, kg) { awake = 0; FOREACH_KSE_IN_GROUP(kg, ke) { ... ke->ke_sched->ske_cpticks = 0; } /* end of kse loop */ /*

* If there are ANY running threads in this KSEGRP, * then don't count it as sleeping. */

/usr/src/sys/kern/sched_4bsd.c

10/09/2007 ecs150 Fall 2007 49

if (awake) { ... kg->kg_slptime = 0; } else { kg->kg_slptime++; } if (kg->kg_slptime > 1) continue; kg->kg_estcpu = decay_cpu(loadfac, kg->kg_estcpu); resetpriority(kg); FOREACH_THREAD_IN_GROUP(kg, td) { if (td->td_priority >= PUSER) { sched_prio(td, kg->kg_user_pri); } } } /* end of ksegrp loop */

/usr/src/sys/kern/sched_4bsd.c

10/09/2007 ecs150 Fall 2007 50

voidsched_clock(struct kse *ke){

struct ksegrp *kg;struct thread *td;

mtx_assert(&sched_lock, MA_OWNED);kg = ke->ke_ksegrp;td = ke->ke_thread;

ke->ke_sched->ske_cpticks++;kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + 1);if ((kg->kg_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {

resetpriority(kg);if (td->td_priority >= PUSER)

td->td_priority = kg->kg_user_pri;}

}

/usr/src/sys/kern/sched_4bsd.c

10/09/2007 ecs150 Fall 2007 51

avg = &averunnable;sx_slock(&allproc_lock);nrun = 0;FOREACH_PROC_IN_SYSTEM(p) {

FOREACH_THREAD_IN_PROC(p, td) {switch (td->td_state) {case TDS_RUNQ:case TDS_RUNNING:

if ((p->p_flag & P_NOLOAD) != 0)goto nextproc;

nrun++; /* XXXKSE */default:

break;}

nextproc: continue;}

}sx_sunlock(&allproc_lock);for (i = 0; i < 3; i++)

avg->ldavg[i] = (cexp[i] * avg->ldavg[i] + nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;

/* * Schedule the next update to occur after 5 seconds, but add a * random variation to avoid synchronisation with processes that * run at regular intervals. */callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)), loadav, NULL);

/usr/src/sys/kern/kern_synch.c

10/09/2007 ecs150 Fall 2007 52

static voidschedcpu(void *arg){ ... FOREACH_PROC_IN_SYSTEM(p) { mtx_lock_spin(&sched_lock); FOREACH_KSEGRP_IN_PROC(p, kg) { awake = 0; FOREACH_KSE_IN_GROUP(kg, ke) { ... ke->ke_sched->ske_cpticks = 0; } /* end of kse loop */ /*

* If there are ANY running threads in this KSEGRP, * then don't count it as sleeping. */

/usr/src/sys/kern/sched_4bsd.c

10/09/2007 ecs150 Fall 2007 53

Mutual ExclusionMutual Exclusion Consistent access to the information. Critical sections. Race conditions.

10/09/2007 ecs150 Fall 2007 54

Critical SectionsCritical Sections No two processes may be simultaneously inside

their critical regions/sections– safety condition

No assumptions may be made about speeds or the number of CPUs

No process running outside of its critical region may block other processes

No process should have to wait forever to enter its critical region/section– liveness condition

10/09/2007 ecs150 Fall 2007 55

Race ConditionRace Condition

4

2

2

1

Withdraw $2 from X:

Read balance X; (1)If X < 2 then exit;Write new X = X - 2;(4)Release $2;

Withdraw $3 from X:

Read balance X;(2)If X < 3 then exit;Write new X = X - 3;(3)Release $3;

10/09/2007 ecs150 Fall 2007 56

10/09/2007 ecs150 Fall 2007 57

How to Prevent?How to Prevent?

Disable Interrupts Busy Waiting and TSL Strict Alternation Protected Critical Sections

Hardware versus software solution….

10/09/2007 ecs150 Fall 2007 58

Let’s try some software solutions!!Let’s try some software solutions!!

Assuming we have only two processes. The solutions should be able to extend to

cover more general cases.

10/09/2007 ecs150 Fall 2007 59

Solution #1Solution #1Process 0 Process 1…. …..while (turn != 0); while (turn != 1);<critical section>; <critical section>;turn = 1; turn = 0;…. …...

What is the problem??

10/09/2007 ecs150 Fall 2007 60

ProblemProblemProcess 0 Process 1…. …..while (turn != 0);<critical section>;turn = 1;…. …...while (turn != 0);…...

while (turn != 1);<critical section>turn = 0;

…... <critical section>;turn = 1;

Maybe a very long period of time…

Blocked…

10/09/2007 ecs150 Fall 2007 61

Solution #2Solution #2

Process 0 Process 1…. …..while (flag[1] = = true); while (flag[0] = = true);flag[0] = true; flag[1] = true;<critical section>; <critical section>;flag[0] = false; flag[1] = false;…. …...

What is the problem??

10/09/2007 ecs150 Fall 2007 62

ProblemProblem

Process 0 Process 1flag[0] = false; flag[1] = false;…. …..while (flag[1] = = true);

while (flag[0] = = true);flag[0] = true;

flag[1] = true;<critical section>;

<critical section>;flag[1] = false;

flag[0] = false;

…. …...

NOTSAFE!!

00011011

10/09/2007 ecs150 Fall 2007 63

Two Properties for METwo Properties for ME

Safe: no two may enter Live: eventually one will win

10/09/2007 ecs150 Fall 2007 64

Solution #3Solution #3

Process 0 Process 1…. …..flag[0] = true; flag[1] = true; while (flag[1] = = true); while (flag[0] = = true);<critical section>; <critical section>;flag[0] = false; flag[1] = false;…. …...

What is the problem??

10/09/2007 ecs150 Fall 2007 65

ProblemProblem

Process 0 Process 1…. …..flag[0] = true;

flag[1] = true; while (flag[1] = = true);

while (flag[0] = = true);

…. …...

Nobody can progress!! (Liveness)

10/09/2007 ecs150 Fall 2007 66

Solution #4Solution #4

Process 0 Process 1…. …..flag[0] = true; flag[1] = true; while (flag[1] = = true) while (flag[0] = = true){ { flag[0] = false; flag[1] = false; <delay a while> <delay a while> flag[0] = true; flag[1] = true;} }<critical section>; <critical section>;flag[0] = false; flag[1] = false;…. …...

10/09/2007 ecs150 Fall 2007 67

ideaideaProcess 0 Process 1….

…..flag[0] = true; flag[1] = true; while (flag[1] = = true && f2 = = true) while (flag[0] = = true && f2 == false){ { flag[0] = false; /*mnbn */ flag[1] = false; /*mnbn*/ flag[2] = ~flag[2]; flag[2] = ~flag[2]; flag[0] = true; /*mnbn */ flag[1] = true; /*mnbn */} }<critical section>; <critical section>;flag[0] = false; flag[1] = false;…. …...

10/09/2007 ecs150 Fall 2007 68

ProblemsProblems

Delay for how long? A different problem: Starvation with a small

but non-zero probability.

10/09/2007 ecs150 Fall 2007 69

Dekker’s AlgorithmDekker’s AlgorithmProcess 0 Process 1…. …..flag[0] = true; flag[1] = true; while (flag[1] = = true) while (flag[0] = = true){ { if (turn = = 1) if (turn = = 0) { {

flag[0] = false; flag[1] = false;while (turn = = 1); while (turn = = 0);flag[0] = true; flag[1] = true;

} }} }<critical section>; <critical section>;turn = 1; turn = 0;flag[0] = false; flag[1] = false;…. …...

10/09/2007 ecs150 Fall 2007 70

Dekker’sDekker’s

Three shared variables to solve the problem:– flag[0], flag[1], and turn

10/09/2007 ecs150 Fall 2007 71

Peterson’s AlgorithmPeterson’s Algorithm

Process 0 Process 1…. …..flag[0] = true; flag[1] = true; turn = 0; turn = 1;while (flag[1] && (turn = = 1)); while (flag[0] && (turn = = 0));<critical section>; <critical section>;flag[0] = false; flag[1] = false;…. …...

Comparing Dekker’s with Peterson’s!!

10/09/2007 ecs150 Fall 2007 72

Peterson’s AlgorithmPeterson’s Algorithm

Process 0 Process 1…. …..flag[0] = true;

flag[1] = true; turn = 0;while (flag[1] && (turn = = 1));

turn = 1;while (flag[0] && (turn = = 0));

<critical section>; <critical section>;flag[0] = false; flag[1] = false;…. …...

10/09/2007 ecs150 Fall 2007 73

WWW stands for WWW stands for What Went WrongWhat Went Wrong??

Process 0 Process 1…. …..flag[0] = true; flag[1] = true; turn = 0; turn = 1;while (flag[1] && (turn = = 1)); while (flag[0] && (turn = = 0));<critical section>; <critical section>;flag[0] = false; flag[1] = false;…. …...

10/09/2007 ecs150 Fall 2007 74

WWW stands for WWW stands for What Went WrongWhat Went Wrong??

Process 0 Process 1…. …..flag[0] = true; flag[1] = true; turn = 0; turn = 1;while (flag[1] && (turn = = 0)); while (flag[0] && (turn = = 1));<critical section>; <critical section>;flag[0] = false; flag[1] = false;…. …...

10/09/2007 ecs150 Fall 2007 75

Previous Exam Question?Previous Exam Question?

Process 0 Process 1…. …..turn = 0; turn = 1;flag[0] = true; flag[1] = true; while (flag[1] && (turn = = 0)); while (flag[0] && (turn = = 1));<critical section>; <critical section>;flag[0] = false; flag[1] = false;…. …...

10/09/2007 ecs150 Fall 2007 76

Peterson’s AlgorithmPeterson’s Algorithm

Process 0 Process 1…. …..flag[0] = true;

flag[1] = true; turn = 0;while (flag[1] && (turn = = 0));

turn = 1;<critical section>;

while (flag[0] && (turn = = 1));flag[0] = false;

<critical section>;flag[1] = false;

…. …...

10/09/2007 ecs150 Fall 2007 77

Peterson’s AlgorithmPeterson’s Algorithm

Process 0 Process 1…. …..flag[0] = true;turn = 0;while (flag[1] && (turn = = 0));<critical section>;

flag[1] = true; turn = 1;while (flag[0] && (turn = = 1));

flag[0] = false;<critical section>;flag[1] = false;

…. …...

10/09/2007 ecs150 Fall 2007 78

Peterson’s AlgorithmPeterson’s Algorithm

Process 0 Process 1…. …..flag[0] = true;turn = 0;

flag[1] = true; turn = 1;

while (flag[1] && (turn = = 0));while (flag[0] && (turn = = 1));<critical section>;flag[1] = false;

<critical section>;flag[0] = false;…. …...

10/09/2007 ecs150 Fall 2007 79

Safety and Liveliness propertiesSafety and Liveliness properties

Process 0 Process 1…. …..flag[0] = true; flag[1] = true; turn = 0; turn = 1;while (flag[1] && (turn = = 0)); while (flag[0] && (turn = = 1));

At the moment when both are in the CS:flag[0] = 1; flag[1] = 1; turn = 0 or 1;

<critical section>; <critical section>;flag[0] = false; flag[1] = false;…. …...

10/09/2007 ecs150 Fall 2007 80

Safety and Liveliness propertiesSafety and Liveliness properties

Process 0 Process 1…. …..flag[0] = true; flag[1] = true; turn = 0;

turn = 1;while (flag[1] && (turn = = 0)); while (flag[0] && (turn = = 1));

flag[0] = 1; flag[1] = 1; turn = 0 or 1;case 1: 0 1 process 1 would not enter!

<critical section>; <critical section>;flag[0] = false; flag[1] = false;…. …...

10/09/2007 ecs150 Fall 2007 81

Safety and Liveliness propertiesSafety and Liveliness properties

Process 0 Process 1…. …..flag[0] = true; flag[1] = true; turn = 0;

turn = 1;while (flag[1] && (turn = = 0)); while (flag[0] && (turn = = 1));

flag[0] = 1; flag[1] = 1; turn = 0 or 1;case 1: 0 1 process 1 would not enter!case 2: 1 0 process 0 would not enter!

<critical section>; <critical section>;flag[0] = false; flag[1] = false;…. …...

10/09/2007 ecs150 Fall 2007 82

Monitor

Multiple Threaded Kernel

10/09/2007 ecs150 Fall 2007 83

TSLTSLtsl register, lock

Do the following jobs atomically (they can not be broken apart):

copies lock to register sets lock to 1

BEFORE: Lock = 1AFTER: Reg = 1 Lock = 1

BEFORE: Lock = 0AFTER: Reg = 0 Lock = 1

10/09/2007 ecs150 Fall 2007 84

Critical Section with TSLCritical Section with TSL

Enter??

Leave??

tsl register, lock

BEFORE: Lock = 1AFTER: Reg = 1 Lock = 1

BEFORE: Lock = 0AFTER: Reg = 0 Lock = 1

10/09/2007 ecs150 Fall 2007 85

Critical Section with TSLCritical Section with TSL

Enter??

loop:  tsl  register, lock       cmp  register, #0       jne  loop

Leave??

move lock, #0

10/09/2007 ecs150 Fall 2007 86

CMPXCHGCMPXCHG

Compare and Exchange

CMPXCHG reg, op1, op2

if (reg == op1)

op1 op2;

else

reg op1;

10/09/2007 ecs150 Fall 2007 87

SemaphoresSemaphores

A “non-busy-waiting” approach. General and Binary Semaphore.

Waiting Queuefor resources

I can only holdN (n=4) units ofresources

not reallynot reallya queue!!!a queue!!!

10/09/2007 ecs150 Fall 2007 88

Binary SemaphoreBinary SemaphorewaitB(s):if (s.value == 1)

s.value = 0;else

place the process in s.queue;block the process;

signalB(s):if (s.queue is empty)

s.value = 1;else

remove P from s.queue;place P in the ready queue;

10/09/2007 ecs150 Fall 2007 89

General SemaphoreGeneral SemaphorewaitG(s):s.count --;if (s.count < 0)

place P in s.queue;block this process;

signalG(s):s.count ++;if (s.count <= 0)

remove P from s.queue;place P in the ready queue;

10/09/2007 ecs150 Fall 2007 90

Binary SemaphoreBinary Semaphore

1. How to do Mutual Exclusion with Semaphores?2. How to implement Semaphores in Software?

10/09/2007 ecs150 Fall 2007 91

Mutual ExclusionMutual Exclusion

mutex_lock

mutex_unlock

10/09/2007 ecs150 Fall 2007 92

ME using SemaphoreME using Semaphore….waitB(semA)<enter critical section>signalB(semA)…..

Waiting Queuefor resources

I can only holdN (n=1) units ofresources

not reallynot reallya queue!!!a queue!!!

10/09/2007 ecs150 Fall 2007 93

SemaphoresSemaphores

10/09/2007 ecs150 Fall 2007 94

MutexesMutexes

A Mutex (Mutual Exclusion) is a data element that allows multiple threads to synchronize their access to shared resources

Like a binary semaphore, a mutex has two states, locked and unlocked

Only one thread can lock a mutex Once a mutex is locked, other threads will block

when they try to lock the same mutex, until the locking mutex unlocks the mutex, at which point one of the waiting thread’s lock will succeed, and the process begins again

10/09/2007 ecs150 Fall 2007 95

Lock and TryLockLock and TryLock

What is the difference?

10/09/2007 ecs150 Fall 2007 96

Mutex vs. CondMutex vs. Cond

mutex_lock

mutex_unlock

cond_wait

cond_signal

10/09/2007 ecs150 Fall 2007 97

Pthread ImplementationPthread Implementation

in pthread_mutex_lock (mutex.c):SET_KERNEL_FLAG;semaphore implementation…CLEAR_KERNEL_FLAG;

in sighandler (signal.c):if (!is_in_kernel)

pthread_schedule_wrapper();…else

sigaddset(…);

10/09/2007 ecs150 Fall 2007 98

SemaphoresSemaphores

10/09/2007 ecs150 Fall 2007 99

HW#2HW#2

2 test programs each team LT kernel

– Please tell us the amount of tickets to set

Contest/test suties– 2xN + M– Is the lottery scehduling working clearly? (e.g., very,

moderate, not really)

– You are encouraged to do cross-team testing before your submission.