The bounded buffer

Preview:

DESCRIPTION

The bounded buffer problem with Semaphore

Citation preview

Bounded Buffer Producer/Consumer Problem

หลายๆเทรดท่ีท างานอยู่ในหนึง่โปรเซสจะใช้หน่วยความจ าและทรัพยากรต่างๆร่วมกนั ดงันัน้จงึต้องมีการประสานงานการท างาน ไม่ให้มีการรบกวนกระบวนการท างานจากเทรดอ่ืนๆ กลไกการท างานทางด้าน synchronization ทัง้หมดของวินโดว์สามารถใช้งานได้กบั เทรด ท่ีอยู่ใน โปรเซส

Traffic Intersection

Critical Sections

shared double balance;

Code for p1 Code for p2

. . . . . .

balance = balance + amount; balance = balance - amount;

. . . . . .

Traffic Intersection(2)

load R1, balance

load R2, amount

load R1, balance

load R2, amount

sub R1, R2

store R1, balance

add R1, R2

store R1, balance

Execution of p1 Execution of p2

//R1=1000 //R2=500

//R1=1000

//R2=500 //R1-R2=500

//balance=500

//R1+R2=1500 //balance=1500

A Semaphore

ผูส้ร้าง Semaphores

• ถกูสร้างในปี 1968 ประมาณ 44 ปีมาแล้ว

• เป็นพืน้ฐานของเทคนิคสมยัใหม่ในการแก้ปัญหาการ synchronization

และยงัคงเป็นวิธีท่ีใช้จดัการการติดตอ่สื่อสาร

กนัของ process ท่ีท างานร่วมกนั

Edsger Wybe Dijkstra

Operation of Semaphores

A Semaphores คือ ตวัแปรจ านวนเตม็ตัง้แต ่0 ขึน้ไป ซึง่เวลาจะเพิ่มหรือลดค่าตวัแปร

จะท าผา่น 2 ฟังก์ชนัดงันี ้

V(s): [s = s + 1] P(s): [while(s == 0) {wait}; s = s - 1]

Bounded Buffer Problem Producer/Consumer Problem

Producer Consumer

Empty Pool

Full Pool

คือปัญหาคลาสสคิทางด้าน synchronization ท่ีน าเสนอโดย Dijkstra เพ่ือนแสดงให้เห็นวิธีการใช้งาน semaphores ในสองรูปแบบ

3 Semaphores

Type 1 : Binary semaphores

1. A mutual exclusion semaphore to prevent the producer and consumer from manipulating the list of buffers at the same time Type 2 : General semaphores (counting semaphores) 2. A semaphore so that the producer can signal the consumer to start processing when it creates a full buffer

3. A semaphore for the consumer to signal the producer when it creates an empty buffer

Animation : Bounded Buffer Problem

• A mutual exclusion semaphore (bufManip)

• General semaphores (empty , full)

Declaration 3 semaphores

Size of Buffers

Design and implement a process with a producer and consumer thread using N different buffers (use a fixed size for N of 20).

Create semaphores

A producer and a consumer thread are created by a parent thread

Producer thread

Consumer thread

Runtime

Terminate thread & ส่ิงท่ีท าเพิ่มเติม

Recommended