18
Bounded Buffer Producer/Consumer Problem

The bounded buffer

Embed Size (px)

DESCRIPTION

The bounded buffer problem with Semaphore

Citation preview

Page 1: The bounded buffer

Bounded Buffer Producer/Consumer Problem

Page 2: The bounded buffer

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

Page 3: The bounded buffer

Traffic Intersection

Critical Sections

shared double balance;

Code for p1 Code for p2

. . . . . .

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

. . . . . .

Page 4: The bounded buffer

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

Page 5: The bounded buffer

A Semaphore

Page 6: The bounded buffer

ผูส้ร้าง Semaphores

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

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

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

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

Edsger Wybe Dijkstra

Page 7: The bounded buffer

Operation of Semaphores

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

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

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

Page 8: The bounded buffer

Bounded Buffer Problem Producer/Consumer Problem

Producer Consumer

Empty Pool

Full Pool

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

Page 9: The bounded buffer

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

Page 10: The bounded buffer

Animation : Bounded Buffer Problem

Page 11: The bounded buffer

• A mutual exclusion semaphore (bufManip)

• General semaphores (empty , full)

Declaration 3 semaphores

Page 12: The bounded buffer

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).

Page 13: The bounded buffer

Create semaphores

Page 14: The bounded buffer

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

Page 15: The bounded buffer

Producer thread

Page 16: The bounded buffer

Consumer thread

Page 17: The bounded buffer

Runtime

Page 18: The bounded buffer

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