chapter 6: process synchronization. 6.2/60 module 6: process synchronization background the...

60
Chapter 6: Process Chapter 6: Process Synchronization Synchronization

Upload: scott-mckinney

Post on 12-Jan-2016

232 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

Chapter 6: Process SynchronizationChapter 6: Process Synchronization

Page 2: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.2/60

Module 6: Process SynchronizationModule 6: Process Synchronization

Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization Monitors

Page 3: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.3/60

BackgroundBackground

Concurrent access to shared data may result in data inconsistency

Maintaining data consistency requires mechanisms to ensure the orderly execution of cooperating processes

Suppose that we wanted to provide a solution to the consumer-producer problem that fills all the buffers. We can do so by having an integer count that keeps track of the number of full buffers. Initially, count is set to 0. It is incremented by the producer after it produces a new buffer and is decremented by the consumer after it consumes a buffer.

P191

Page 4: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.4/60

Producer Producer

while (true) {

/* produce an item and put in nextProduced */

while (count == BUFFER_SIZE)

; // do nothing

buffer [in] = nextProduced;

in = (in + 1) % BUFFER_SIZE;

count++;

}

Page 5: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.5/60

ConsumerConsumer

while (true) {

while (count == 0)

; // do nothing

nextConsumed = buffer[out];

out = (out + 1) % BUFFER_SIZE;

count--;

/* consume the item in nextConsumed

}

Page 6: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.6/60

Race ConditionRace Condition

count++ could be implemented as

register1 = count register1 = register1 + 1 count = register1

count-- could be implemented as

register2 = count register2 = register2 - 1 count = register2

P192

Page 7: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.7/60

Race ConditionRace Condition

Consider this execution interleaving with “count = 5” initially:

S0: producer execute register1 = count {register1 = 5}S1: producer execute register1 = register1 + 1 {register1 = 6} S2: consumer execute register2 = count {register2 = 5} S3: consumer execute register2 = register2 - 1 {register2 = 4} S4: producer execute count = register1 {count = 6 } S5: consumer execute count = register2 {count = 4}

Correct result: count=5

P193

Page 8: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.8/60

Race ConditionRace Condition

A situation like this, where several processes access and manipulate the same data concurrently and the outcome of the execution depends on the particular order in which the access takes place, is called a race condition.

we need to ensure that only one process at a time can be manipulating the variable count. To make such a guarantee, we require that the processes be synchronized in some way.

竞争条件( Race Condition ) * 多个进程并发访问和维护同样的数据, * 执行的结果依赖于访问发生时的特定顺序。

P193

Page 9: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.9/60

Critical-Section ProblemCritical-Section Problem

Consider a system consisting of n processes {P0, P 1 , ..., Pn-1). Each process has a segment of code, called a critical section, in which the process may be changing common variables, updating a table, writing a file, and so on.

when one process is executing in its critical section, no other process is to be allowed to execute in its critical section.

Each process must request permission to enter its critical section. The section of code implementing this request is the entry section.

Page 10: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.10/60

Critical-Section ProblemCritical-Section Problem The critical section may be followed by an exit section.

The remaining code is the remainder section.

Page 11: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.11/60

临界资源临界资源

临界资源( Critical resource ) 并发进程可以共享系统中的各种资源,但是系统中的某

些资源,例如打印机、磁带机、表格、等,虽然他们可以提供给多个进程使用,但在一段时间内却只允许一个进程访问该资源。当一个进程正在访问该资源时,其他欲访问该资源的进程必须等待,仅当该进程访问完并释放该资源后,才允许另一进程对该资源进行访问。把在一段时间内只允许一个进程访问的资源称为临界资源。即临界资源需要互斥访问。

临界区( Critical Section ) 把在每个进程中访问临界资源的那段代码称为临界区。

当一个进程正在临界区执行时,其他进程不允许进入他们的临界区执行。

Page 12: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.12/60

Solution to Critical-Section ProblemSolution to Critical-Section Problem

A solution to the critical-section problem must satisfy the following four requirements:

1. Mutual Exclusion - If process Pi is executing in its critical section, then no other processes can be executing in their critical sections

2. Progress - If no process is executing in its critical section and there exist some processes that wish to enter their critical section, then the selection of the processes that will enter the critical section next cannot be postponed indefinitely

P194

Page 13: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.13/60

Solution to Critical-Section ProblemSolution to Critical-Section Problem

3. Bounded Waiting - A bound must exist on the number of times that other processes are allowed to enter their critical sections after a process has made a request to enter its critical section and before that request is granted

4. No Busy waiting- 让权等待,不能进入临界区,应释放 CPU

Page 14: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.14/60

Initial Attempts to Solve ProblemInitial Attempts to Solve Problem

Only 2 processes, P0 and P1

General structure of process Pi (other process Pj)

do {

entry section

critical section

exit section

reminder section

} while (1);

Processes may share some common variables to synchronize their actions.

Page 15: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.15/60

Algorithm 1Algorithm 1

Shared variables: int turn;

initially turn = 0 turn= 0 P0 can enter its critical section

Satisfies mutual exclusion, but not progress

Process P0

do { while (turn != 0) ; critical section turn = 1;reminder section} while (1);

Process P1

do { while (turn != 1) ; critical section turn = 0;reminder section} while (1);

Page 16: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.16/60

Algorithm 2Algorithm 2 Shared variables

boolean flag[2];initially flag [0] = flag [1] = false.

flag [i] = true Pi ready to enter its critical section

Satisfies mutual exclusion, but not progress requirement.

Process P0

do { flag[0] := true; while (flag[1]) ; critical section flag [0] = false; remainder section} while (1);

Process P1

do { flag[1] := true; while (flag[0]) ; critical section flag [1] = false; remainder section} while (1);

Page 17: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.17/60

Algorithm 3--- Peterson’s SolutionAlgorithm 3--- Peterson’s Solution

Combined shared variables of algorithms 1 and 2.

Meets all three requirements; solves the critical-section problem for two processes.

P196

Process P0

do { flag [0]:= true; turn = 1; while (flag [1] and turn = 1); critical section flag [0] = false; remainder section } while (1);

Process P1

do { flag [1]:= true; turn = 0; while (flag [0] and turn = 0); critical section flag [1] = false; remainder section } while (1);

Page 18: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.18/60

分析分析

当两个进程几乎同时到达,同时将 flag[0] 与flag[1] 同时 true ;同时将 turn 置为 0 与 1 ,但只有一个能够维持; 这样,可以保证两个进程的while 循环有一个能够满足,另一个不满足。只允许不满足 while 循环条件的一个进程进入临界区,而另一个(满足 while 循环条件)进程等待(满足互斥访问);并且一个进程必然能进入临界区(满足有空让进),且当该进程退出临界区时,将相应的 flag[] 置为 false ,使另一个进程的 while 循环条件不满足,该进程可以使用临界区(满足有限等待)。

Page 19: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.19/60

Synchronization HardwareSynchronization Hardware

Many systems provide hardware support for critical section code

Uni-processor – could disable interrupts Currently running code would execute without

preemption Modern machines provide special atomic hardware

instructions Atomic = non-interruptable

P197

Page 20: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.20/60

TestAndSet Instruction TestAndSet Instruction

Definition:

boolean TestAndSet (boolean *target)

{

boolean rv = *target;

*target = TRUE;

return rv:

}

Page 21: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.21/60

Solution using TestAndSetSolution using TestAndSet

Shared Boolean variable lock, initialized to false. Solution:

while (true) {

while ( TestAndSet (&lock ))

; /* do nothing

// critical section

lock = FALSE;

// remainder section

}

Page 22: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.22/60

Swap InstructionSwap Instruction

Definition:

void Swap (boolean *a, boolean *b)

{

boolean temp = *a;

*a = *b;

*b = temp:

}

P198

Page 23: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.23/60

Solution using SwapSolution using Swap

Shared Boolean variable lock initialized to FALSE; Each process has a local Boolean variable key.

Solution:

while (true) {

key = TRUE;

while ( key == TRUE)

Swap (&lock, &key );

// critical section

lock = FALSE;

// remainder section

}

Page 24: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.24/60

SemaphoreSemaphore

Semaphore S – integer variable Two standard operations modify S: wait() and signal()

Originally called P() and V() Can only be accessed via two indivisible (atomic)

operations

P200

Page 25: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.25/60

Semaphore Semaphore 类型类型

Counting semaphores can be used to control access to a given resource consisting of a finite number of instances.

The semaphore is initialized to the number of resources available.

Each process that wishes to use a resource performs a wait() operation on the semaphore

When a process releases a resource, it performs a signal() operation

When the count for the semaphore goes to 0, all resources are being used. After that, processes that wish to use a resource will block until the count becomes greater than 0.

P201

Page 26: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.26/60

Semaphore Semaphore 类型类型

The value of a binary semaphore can range only between 0 and 1.

On some systems, binary semaphores are known as mutex locks, as they are locks that provide mutual exclusion

Page 27: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.27/60

Semaphore as General Synchronization ToolSemaphore as General Synchronization Tool

Provides mutual exclusion

Semaphore S; // initialized to 1

wait (S);

Critical Section

signal (S);

Page 28: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.28/60

Solve Various Synchronization ProblemsSolve Various Synchronization Problems

consider two concurrently running processes: P1 with a statement S1 and P2 with a statement S2.

Suppose we require that S2 be executed only after S1 has completed.

We can implement this scheme readily by letting P1 and P2 share a common semaphore synch, initialized to 0

P1 P2

S1;signal (synch) ;

wait (synch) ;S2;

P201

Page 29: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.29/60

Semaphore ImplementationSemaphore Implementation

Must guarantee that no two processes can execute wait () and signal () on the same semaphore at the same time

Thus, implementation becomes the critical section problem where the wait and signal code are placed in the critical section.

Note that applications may spend lots of time in critical sections and therefore this is not a good solution.

P202

Page 30: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.30/60

Semaphore Implementation with no Busy waitingSemaphore Implementation with no Busy waiting

With each semaphore there is an associated waiting queue. Each entry in a waiting queue has two data items:

value (of type integer)

pointer to next record in the list

Two operations:

block – place the process invoking the operation on the appropriate waiting queue.

wakeup – remove one of processes in the waiting queue and place it in the ready queue.

Page 31: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.31/60

Semaphore Implementation with no Busy waitingSemaphore Implementation with no Busy waiting (Cont.)(Cont.)

Page 32: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.32/60

Semaphore Implementation with no Busy waitingSemaphore Implementation with no Busy waiting (Cont.)(Cont.)

Page 33: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.33/60

分析分析 value 的初值表示系统中某类资源的数目,因而又称为

资源信号量, 每次的 wait 操作,意味着进程请求一个单位的资源,描

述为 value-- ;当 value<0 时,表示资源已经分配完毕,因而进程自我阻塞,放弃处理机,添加到等待进程队列中。此时, value 的绝对值表示在该信号量链中已经阻塞的进程的数目。

每次 signal 操作表示执行进程释放一个单位资源,故表示为 value++ ,表示资源数目加 1 。若加 1 后仍满足value<=0 ,表示该信号量链中仍有等该资源的进程被阻塞,故还应该将其中的一个进程唤醒。

Page 34: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.34/60

实现机制实现机制 The list of waiting processes can be easily implemented

by a link field in each process control block (PCB).

The critical aspect of semaphores is that they be executed atomically. We must guarantee that no two processes can execute wait ( ) and signal ( ) operations on the same semaphore at the same time.

in a single-processor environment (that is, where only one CPU exists), we can solve it by simply inhibiting interrupts during the time the wait ( ) and signal () operations are executing.

wait ()和 signal ()必须成对出现,使用资源后必须释放资源。

P203

Page 35: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.35/60

Deadlock and StarvationDeadlock and Starvation

Deadlock – two or more processes are waiting indefinitely for an event that can be caused by only one of the waiting processes

Let S and Q be two semaphores initialized to 1

P0 P1

wait (S); wait (Q);

wait (Q); wait (S);

. .

signal (S); signal (Q);

signal (Q); signal (S);

Starvation – indefinite blocking. A process may never be removed from the semaphore queue in which it is suspended.

P204

Page 36: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.36/60

Classical Problems of SynchronizationClassical Problems of Synchronization

Bounded-Buffer Problem

Readers and Writers Problem

Dining-Philosophers Problem

Page 37: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.37/60

Bounded-Buffer ProblemBounded-Buffer Problem

N buffers, each can hold one item

Semaphore mutex initialized to the value 1

用于整个缓冲区的互斥 Semaphore full initialized to the value 0

表示占用的缓冲区数目或请求情况 Semaphore empty initialized to the value N.

表示空闲的缓冲区数目或请求情况

P205

Page 38: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.38/60

Bounded Buffer Problem (Cont.)Bounded Buffer Problem (Cont.)

Wait(empty)

Wait(mutex)

修改缓冲区

signal(mutex)

Signal(full)

Wait(full)

Wait(mutex)

修改缓冲区

signal(mutex)

signal(empty)

生产者 消费者

Page 39: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.39/60

Readers-Writers ProblemReaders-Writers Problem

A data set is shared among a number of concurrent processes

Readers – only read the data set; they do not perform any updates

Writers – can both read and write.Problem – allow multiple readers to read at the same time. Only one single writer can access the shared data at the same time.

P206

Page 40: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.40/60

Readers-Writers ProblemReaders-Writers Problem

The readers-writers problem has several variations, all involving priorities.

The first readers-writers problem, requires that no reader will be kept waiting unless a writer has already obtained permission to use the shared object. In other words, no reader should wait for other readers to finish simply because a writer is waiting.

The second readers-writers problem, requires that, once a writer is ready, that writer performs its write as soon as possible. In other words, if a writer is waiting to access the object, no new readers may start reading.

A solution to either problem may result in starvation. In the first case, writers may starve; in the second case, readers may starve.

Page 41: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.41/60

Readers-Writers ProblemReaders-Writers Problem

first readers-writers problem

Semaphore mutex initialized to 1.

用于对 readerCount 的互斥访问 Semaphore wrt initialized to 1.

用于读者 - 写者以及写者 - 写者之间的互斥 Integer readcount initialized to 0.

标识读者数目

Page 42: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.42/60

Wait(mutex);

++readerCount;

if (readerCount==1)

Wait(wrt);

Signal(mutex);

执行具体读操作

wait(mutex);

--readerCount;

if (readerCount==0)

signal(wrt);

signal(mutex);

Wait(wrt);

执行具体写操作

signal(wrt);

读者 写者

Page 43: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.43/60

Dining-Philosophers ProblemDining-Philosophers Problem

问题描述

P208

Page 44: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.44/60

Dining-Philosophers ProblemDining-Philosophers Problem

The dining-philosophers problem is considered a classic synchronization problem neither because of its practical importance nor because computer scientists dislike philosophers but because it is an example of a large class of concurrency-control problems.

It is a simple representation of the need to allocate several resources among several processes in a deadlock-free and starvation-free manner.

Page 45: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.45/60

Dining-Philosophers Problem (Cont.)Dining-Philosophers Problem (Cont.)

Semaphore chopstick [5] initialized to 1 The structure of Philosopher i:

While (true) {

wait ( chopstick[i] );

wait ( chopStick[ (i + 1) % 5] );

// eat

signal ( chopstick[i] );

signal (chopstick[ (i + 1) % 5] );

// think

}

Page 46: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.46/60

Dining-Philosophers Problem (Cont.)Dining-Philosophers Problem (Cont.)

it could create a deadlock. Suppose that all five philosophers become hungry simultaneously and each grabs her left chopstick. All the elements of chopstick will now be equal to 0. When each philosopher tries to grab her right chopstick, she will be delayed forever.

解决的办法 至多允许四个哲学家进餐; 仅当左右筷子均可用时,才允许他拿起筷子进餐; 规定奇数号哲学家先拿左边的筷子,再去拿右边的筷

子。而偶数号哲学家则相反。

P209

Page 47: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.47/60

Problems with SemaphoresProblems with Semaphores

incorrect use of semaphore operations:

signal (mutex) …. wait (mutex)

wait (mutex) … wait (mutex)

Omitting of wait (mutex) or signal (mutex) (or both)

信号量机制虽能解决同步问题,但需要程序员显式地编程

Page 48: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.48/60

MonitorsMonitors

A high-level abstraction that provides a convenient and effective mechanism for process synchronization

Only one process may be active within the monitor at a time

monitor monitor-name

{

// shared variable declarations

procedure P1 (…) { …. }

procedure Pn (…) {……}

Initialization code ( ….) { … }

…}P209

Page 49: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.49/60

MonitorsMonitors

一个管程定义了一个数据结构和能为并发进程所执行的一组操作,这组操作能同步进程和改变管程中的数据。 [ 面向对象的思想 ]

管程相当于围墙,它把共享变量和对它进行操作的若干过程围了起来,所有进程要访问临界资源时,都必须经过管程(相当于通过围墙的门)才能进入,而管程每次只允许一个进程进入管程,从而实现了进程之间的互斥。

Page 50: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.50/60

Schematic view of a MonitorSchematic view of a Monitor

Page 51: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.51/60

Condition VariablesCondition Variables

the monitor construct, as defined so far, is not sufficiently powerful for modeling some synchronization schemes.

For this purpose, we need to define additional synchronization mechanisms. These mechanisms are provided by the condition construct.

condition x, y; Two operations on a condition variable:

x.wait () – a process that invokes the operation is

suspended. x.signal () – resumes one of processes (if any) that

invoked x.wait ()

P211

Page 52: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.52/60

Condition VariablesCondition Variables

The x . Signal() operation resumes exactly one suspended process. If no process is suspended, then the signal() operation has no effect; that is, the state of x is the same as if the operation had never been executed.

Contrast this operation with the signal () operation associated with semaphores, which always affects the state of the semaphore.

Page 53: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.53/60

Monitor with Condition VariablesMonitor with Condition Variables

Page 54: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.54/60

Condition VariablesCondition Variables

Now suppose that, when the x . signal ( ) operation is invoked by a process P, there is a suspended process Q associated with condition x. Clearly, if the suspended process Q is allowed to resume its execution, the signaling process P must wait. Otherwise, both P and Q would be active simultaneously within the monitor.

Note, however, that both processes can conceptually continue with their execution.

Two possibilities exist: 1. Signal and wait. P either waits until Q leaves the

monitor or waits for another condition. 2. Signal and continue. Q either waits until P leaves

the monitor or waits for another condition.

Page 55: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.55/60

Solution to Dining PhilosophersSolution to Dining Philosophers

monitor DP

{

enum { THINKING; HUNGRY, EATING) state [5] ;

condition self [5];

void pickup (int i) {

state[i] = HUNGRY;

test(i);

if (state[i] != EATING) self [i].wait;

}

P214

Page 56: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.56/60

Solution to Dining PhilosophersSolution to Dining Philosophers

void putdown (int i) {

state[i] = THINKING;

// test left and right neighbors

test((i + 4) % 5);

test((i + 1) % 5);

}

void test (int i) {

if ( (state[(i + 4) % 5] != EATING) &&

(state[i] == HUNGRY) &&

(state[(i + 1) % 5] != EATING) ) {

state[i] = EATING ;

self[i].signal () ;

}

}

Page 57: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.57/60

Solution to Dining Philosophers Solution to Dining Philosophers

initialization_code() {

for (int i = 0; i < 5; i++)

state[i] = THINKING;

}

}

Page 58: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.58/60

Solution to Dining Philosophers Solution to Dining Philosophers

Each philosopher I invokes the operations pickup()

and putdown() in the following sequence:

dp.pickup (i)

EAT

dp.putdown (i)

Page 59: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

6.59/60

Windows XP SynchronizationWindows XP Synchronization

临界区( Critical Section ):临界区不是内核对象,在用户态实现了同一进程中线程的互斥。由于使用时不需要从用户态切换到核心态,所以速度很快,但其缺点是不能跨进程同步,同时不能指定阻塞时的等待时间,只能无限等待。

互斥体:( Mutex ):互斥体实现了和临界区类似的互斥功能,但区别在于:互斥体是内核对象,可以实现跨进程互斥,但需要在用户态和核心态之间切换,速度比关键节慢得多,可以指定阻塞时的等待时间。

事件( Event ):事件也是内核对象,具有“信号态”和“无信号态”两种状态。当某一线程等待一个事件时,如果事件为信号态,将继续执行,如果事件为无信号态,那么线程被阻塞。能够指定阻塞时的等待时间。

信号量( Semaphore ):信号量是一个资源计数器,当某线程获取某信号量时,信号量计数首先减 1 ,如果计数小于 0 ,那么该线程被阻塞;当某信号量被释放时,信号量计数首先加 1 ,如果计数大于或等与 0 ,那么唤醒某被阻塞的线程并执行之。

Page 60: Chapter 6: Process Synchronization. 6.2/60 Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization

Homework: 1Homework: 1 、、 33 、、 99 、、 1111 、、 1515

End of Chapter 6End of Chapter 6