CPT104操作系统笔记(Lecture 3 Process Synchronization)

Background

What is Process Synchronization (PS)?
PS is the task of coordinating the execution of processes in a way that no two processes can have access to the same shared data and resources.
Process Synchronization
Concurrent access(并发存取) to shared data may result in data inconsistency
Maintaining data consistency requires mechanisms to ensure the orderly execution of cooperating processes.
Race condition: 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.
        • To prevent this, concurrent processes must be synchronized
          确保一次只有一个进程可以操作变量计数器

The Critical Section Problem

Each (concurrent) process has a code segment, called Critical Section(CS) , in which the shared data is accessed
CS = codes that reference one variable in a “read-update-write” fashion

 

 Critical section to prevent a race condition: lose some parallelism, but regain correctness

 CS problem

Concurrent processes come into conflict when they use the same resource (competitively or shared)
        for example: I/O devices, memory, processor time, clock
3 requirements for the solution:
Mutual Exclusion : When a process/thread is executing in its critical section, no other process/threads can be executing in their critical sections.
Progress : If no process/thread is executing in its critical section, it must be possible to negotiate who will proceed next into CS.
Bounded Waiting : the waiting time of a process/thread outside a critical section should be Limited (otherwise the process/thread could suffer from starvation )

Software solutions (Peterson's Solution)

Peterson’s Solution  (formulated by Gary L. Peterson in 1981)

Only 2 processes, P0 and P1

are not guaranteed to work on modern computer architectures

Peterson’s solution requires the two processes to share two data items:

int turn;                              //表示轮到谁进入 critical section
boolean flag[2];                 // initialized to FALSE    指示进程何时想要进入它们的CS
                                            flag[i] = true表示进程Pi已经准备好(i = 0,1)

Peterson's Algorithm

 

Proof of Correctness

Mutual Exclusion:For both P0 and P1 to be in their CS:

                                both flag[0] and flag[1] must be true and:

                                turn=0 and turn=1 (at same time): impossible
Progress: The shared variable turn assures that only one process at a time can be blocked, and the flag variable allows one process to release the other when exiting their critical section
Bounded Waiting: As each process enters their entry section, they set the turn variable to be the other processes turn. Since no process ever sets it back to their own turn, this ensures that each process will have to let the other process go first at most one time before it becomes their turn again
 

Drawbacks of Software Solutions

• Complicated to program
• Busy waiting (wasted CPU cycles)
It would be more efficient to block processes that are waiting (just as if they had requested I/O).
  This suggests implementing the permission/waiting function in the Operating System

Hardware Solutions

Locks

Single-processor environment - could disable interrupts
Effectively stops scheduling other processes.
Currently running code would execute without preemption

 Initially, lock value is set to 0

  Lock value = 0 means the critical section is currently vacant and no process is present inside it.
  Lock value = 1 means the critical section is currently occupied and a process is present inside it.
satisfy the mutual exclusion requirement
do not guarantee bounded waiting .
Multi-processor environment
- modern machines provide special atomic hardware instructions.
Atomic mean non-interruptable (i.e., the instruction executes as one unit)

- a global variable lock is initialized to 0.

- the only P i that can enter CS is the one which finds lock=0
- this Pi excludes all other Pj by setting lock to 1.

Advantages

Applicable to any number of processes on either a single processor or multiple processors sharing main memory

• Simple and easy to verify

It can be used to support multiple critical sections; each critical section can be defined by its own variable

Disadvantages

Busy-waiting is employed, thus while a process is waiting for access to a critical section it continues to consume processor time
Starvation is possible when a process leaves a critical section, and more than one process is waiting
Deadlock is possible if a low priority process has the critical region and a higher priority process needs, the higher priority process will obtain the processor to wait for the critical region

Operating Systems and Programming Language Solutions

Special variables: mutex, semaphore (互斥量、信号量)

Mutex Lock / Mutual exclusion

The simplest tool

Mutex is a software tool
Mutex allow multiple process / thread to access a single resource but not simultaneously.
To enforce mutex at the kernel level and prevent the corruption of shared data structures - disable interrupts for the smallest number of instructions is the best way.
To enforce mutex in the software areas – use the busy-wait mechanism
- busy-wait mechanism or busy-looping or spinning is a technique in which a process/thread repeatedly checks to see if a lock is available.
Using mutexes is to acquire a lock prior to entering a criticalsection, and to release it when exiting

 Mutex object is locked or unlocked by the process requesting or releasing the resource

This type of mutex lock is called a spinlock because the process “spins” while waiting for the lock to become available.

Semaphore

proposed by Dijkstra in 1965

a technique to manage concurrent processes by using a simple integer value

an integer variable which is non-negative and shared between threads
This variable is used to solve the critical section problem and to achieve process synchronization in the multiprocessing environment.
accessed only through two standard atomic operations: wait() and signal()

For n processes
Initialize semaphore S to 1
Then only one process is allowed
  into CS ( mutual exclusion )
To allow k processes into CS at a
  time, simply initialize mutex to k
 

two main types of semaphores:  

counting semaphore - allow an arbitrary resource count. Its value can range over an unrestricted domain. It is used to control access to a resource that has multiple instances.

binary semaphore - also known as mutex lock. It can have only 2 values: 0 and 1(initialized to 1). It is used to implement the solution of critical section problem with multiple processes.

Operating systems often distinguish between counting and binary semaphores.

Counting Semaphores

The semaphore S is initialized to the number of available resources.
Each process that wishes to use a resource performs a wait() opera tion on the semaphore (thereby decrementing the number of available resources ).
When a process releases a resource, it performs a signal() op eration ( incrementing the number of available resources ).
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.

Binary Semaphores

Implement mutual exclusion, hence it is often called Mutex.

value is restricted to 0 and 1

The wait() operation only works when the semaphore is 1
and the signal() operation succeeds when semaphore is 0 .

It is sometimes easier to implement binary semaphoresthan counting semaphores.

Same issues of semaphore

Starvation and Deadlock are situations that occur when the processes that require a resource are delayed for a long time.
Deadlock is a condition where no process proceeds for execution, and each waits for resources that have been acquired by the other processes.
in Starvation , process with high priorities continuously uses the resources preventing low priority process to acquire the resources.

Classical Problems of Synchronization(5.7)

The Bounded-Buffer / Producer-Consumer Problem

 The mutex binary semaphore provides mutual exclusion for accesses to the buffer pool and is initialized to the value 1.

The empty and full semaphores count the number of empty and full buffers.

The Readers–Writers Problem

A data set is shared among a number of concurrent processes.
Only one single writer can access the shared data at the same time , any other writers or readers must be blocked.
Allow multiple readers to read at the same time , any writers must be blocked.
Solution : Acquiring a reader–writer lock requires specifying the mode of the lock: either read or write access.

The Dining-Philosophers Problem

How to allocate several resources among several processes.
Several solutions are possible:
• Allow only 4 philosophers to be hungry at a time.
• Allow pickup only if both chopsticks are available. ( Done in critical section )
• Odd # philosopher always picks up left chopstick 1 st ,
  Even # philosopher always picks up right chopstick 1 st .

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值