Lecture 16 ReadersWriters Problem and Message Passing 1
Lecture 16: Readers-Writers Problem and Message Passing 1
Review: Mutual Exclusion Solutions • Software solution – Disabling interrupts – Strict alternation – Peterson’s solution • Hardware solution – TSL/XCHG • Semaphore • Conditional variables • POSIX standards 2
Review: Deadlock proc 1( ) { pthread_mutex_lock(&m 1); /* use object 1 */ pthread_mutex_lock(&m 2); proc 2( ) { pthread_mutex_lock(&m 2); /* use object 2 */ pthread_mutex_lock(&m 1); /* use objects 1 and 2 */ pthread_mutex_unlock(&m 2); pthread_mutex_unlock(&m 1); pthread_mutex_unlock(&m 2); } } Thread 1 Mutex m 1 Thread 2 Mutex m 2 Thread 2 3
DEADLOCK 4
In this lecture • Readers/Writer problem • Message passing 5
Classical problems • Dining Philosophers Problem • Readers-Writers Problem 6
Readers-Writers Problem • Multiple threads reading/writing a database • Many threads can read simultaneously • Only one can be writing at any time – When a writer is executing, nobody else can read or write 7
Readers-Writers Problem • Database has multiple threads operating – Many threads can read simultaneously – Only one can be writing at any time – When a writer is executing, nobody else can read or write • Example: Multithreaded web server cache http: //www. theserverside. com/resources/articles/Readers-Writers/article. html 8
Solution Idea • Readers: – First reader locks the database – If a reader inside, other readers enter without locking again – Checking for readers occurs within a mutex • Writer: – Always lock database before entering 9
Readers-Writers READER: While (1) { down(protector); rc++; if (rc == 1) //first reader down(database); up(protector); WRITER: While (1) { generate_data(); down(database); write(); up(database); } read(); down(protector); rc--; If (rc == 0) then // last one up(database); up(protector); …. } Two semaphores: database protector Initial: protector=1, database =1 rc =0 10
Writer Starvation • Readers might continuously enter while a writer waits • Writer Priority Solution? – What does it mean to give writer priority? • What is a fair solution? – Give a specification 11
Interprocess/thread communication • Shared variables – Mutual exclusion • Message passing 12
Message Passing • No shared variables • Two primitives: – send (destination, message) – receive (destination, message) • Usually blocks till a message arrives • Non-blocking version also usually available • Message Passing Interface (MPI) 13
Issues • Across different machines, message passing is the real thing • Many issues to consider: – Marshaling data into messages – Provide reliable transmission across unreliable links? – Event-driven mode of programming • Computer Networking: deals with sending messages across machines 14
- Slides: 14