CONDITION VARIABLE. Announcements  Quiz  Getting the big picture  Programming assignments  Cooperation  Lecture is cut 20 mins short for Quiz and.

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Concurrency: Deadlock and Starvation Chapter 6. Deadlock Permanent blocking of a set of processes that either compete for system resources or communicate.
Chapter 6: Process Synchronization
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
1 Semaphores and Monitors CIS450 Winter 2003 Professor Jinhua Guo.
02/27/2004CSCI 315 Operating Systems Design1 Process Synchronization Deadlock Notice: The slides for this lecture have been largely based on those accompanying.
CY2003 Computer Systems Lecture 05 Semaphores - Theory.
SPL/2010 Liveness And Performance 1. SPL/2010 Performance ● Throughput - How much work can your program complete in a given time unit? ● Example: HTTP.
Classic Synchronization Problems
Synchronization Principles Gordon College Stephen Brinton.
Ken Birman. Dining Philosophers A problem that was invented to illustrate some issues related to synchronization with objects Our focus here is on the.
02/19/2010CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
– 1 – , F’02 Traditional View of a Process Process = process context + code, data, and stack shared libraries run-time heap 0 read/write data Program.
1 Last Time: Locks & Semaphores Implementing locks Test & Set Busy waiting Block waiting Semaphores Generalization of locks.
Avishai Wool lecture Introduction to Systems Programming Lecture 4 Inter-Process / Inter-Thread Communication.
Concurrency: Deadlock and Starvation Chapter 6. Revision Describe three necessary conditions for deadlock Which condition is the result of the three necessary.
Monitors CSCI 444/544 Operating Systems Fall 2008.
IPC and Classical Synchronization Problems
Dining Philosophers and the Deadlock Concept. Announcements Homework 2 and Project 2 Design Doc due Today –Make sure to look at the lecture schedule to.
Computer Science 162 Discussion Section Week 3. Agenda Project 1 released! Locks, Semaphores, and condition variables Producer-consumer – Example (locks,
Condition Variables Revisited Copyright ©: University of Illinois CS 241 Staff1.
Silberschatz, Galvin and Gagne ©2007 Operating System Concepts with Java – 7 th Edition, Nov 15, 2006 Chapter 6(b): Synchronization.
Chapter 6 Concurrency: Deadlock and Starvation Operating Systems: Internals and Design Principles, 6/E William Stallings Dave Bremer Otago Polytechnic,
CS4231 Parallel and Distributed Algorithms AY 2006/2007 Semester 2 Lecture 2 (19/01/2006) Instructor: Haifeng YU.
Monitors High-level synchronization construct that allows the safe sharing of an abstract data type among concurrent processes. monitor monitor-name {
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Classical problems.
Critical Problem Revisit. Critical Sections Mutual exclusion Only one process can be in the critical section at a time Without mutual exclusion, results.
Operating Systems CMPSC 473 Mutual Exclusion Lecture 14: October 14, 2010 Instructor: Bhuvan Urgaonkar.
Programming with POSIX* Threads Intel Software College.
1 Concurrent Programming. 2 Outline Semaphores for Shared Resources –Producer-consumer problem –Readers-writers problem Example –Concurrent server based.
Thread Synchronization Tutorial #8 CPSC 261. A thread is a virtual processor Each thread is provided the illusion that it owns a core – Copy of the registers.
4061 Session 21 (4/3). Today Thread Synchronization –Condition Variables –Monitors –Read-Write Locks.
Synchronizing Threads with Semaphores
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Synchronization.
Pthreads #include pthread_t tid ; //thread id. pthread_attr_t attr ; void *sleeping(void *); /* thread routine */ main() { int time = 2 ; pthread_create(&tid,
Chapter 6: Process Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Module 6: Process Synchronization Background The.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Lecture 11: Synchronization (Chapter 6, cont)
1 Condition Variables CS 241 Prof. Brighten Godfrey March 16, 2012 University of Illinois.
13/03/07Week 21 CENG334 Introduction to Operating Systems Erol Sahin Dept of Computer Eng. Middle East Technical University Ankara, TURKEY URL:
Synchronisation Examples
CENG334 Introduction to Operating Systems Erol Sahin Dept of Computer Eng. Middle East Technical University Ankara, TURKEY URL:
Semaphores Ref: William Stallings G.Anuradha. Principle of a Semaphore Two or more processes can cooperate by means of simple signals, such that a process.
Chapter 6 P-Threads. Names The naming convention for a method/function/operation is: – pthread_thing_operation(..) – Where thing is the object used (such.
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 13: Condition Variable, Read/Write Lock, and Deadlock.
1 Previous Lecture Overview  semaphores provide the first high-level synchronization abstraction that is possible to implement efficiently in OS. This.
CSC 360 Instructor: Kui Wu More on Process Synchronization Semaphore, Monitor, Condition Variables.
Thread S04, Recitation, Section A Thread Memory Model Thread Interfaces (System Calls) Thread Safety (Pitfalls of Using Thread) Racing Semaphore.
Dining Philosophers & Monitors Questions answered in this lecture: How to synchronize dining philosophers? What are monitors and condition variables? What.
CSCI1600: Embedded and Real Time Software Lecture 17: Concurrent Programming Steven Reiss, Fall 2015.
Operating System Concepts and Techniques Lecture 16 Deadlock and starvation-2 M. Naghibzadeh Reference M. Naghibzadeh, Operating System Concepts and Techniques,
Classic problems of Synchronization : Producers/Consumers problem: The producers/ consumers problem may be stated as follows: Given a set of cooperating.
Rensselaer Polytechnic Institute CSCI-4210 – Operating Systems David Goldschmidt, Ph.D.
Chien-Chung Shen CIS/UD
Interprocess Communication Race Conditions
Dining Philosophers Five philosophers sit around a table
Chapter 5: Process Synchronization – Part 3
2.4 Classic IPC Problems Dining philosophers Readers and writers
Instructor: Randy Bryant
CSCI 511 Operating Systems Chapter 5 (Part C) Monitor
Chapter 5: Process Synchronization (Con’t)
Recitation 14: Proxy Lab Part 2
Liveness And Performance
Module 7a: Classic Synchronization
Chapter 7: Synchronization Examples
Synchronization: Advanced CSCI 380: Operating Systems
CSCI1600: Embedded and Real Time Software
Lecture 20: Synchronization
CS 144 Advanced C++ Programming May 7 Class Meeting
Presentation transcript:

CONDITION VARIABLE

Announcements  Quiz  Getting the big picture  Programming assignments  Cooperation  Lecture is cut 20 mins short for Quiz and in-class activity.

Today  Races  Deadlocks  Dining Philosopher's Problem  Condition Variable

One Worry: Races  A race occurs when correctness of the program depends on one thread reaching point x before another thread reaches point y /* a threaded program with a race */ int main() { pthread_t tid[N]; int i; for (i = 0; i < N; i++) Pthread_create(&tid[i], NULL, thread, &i); for (i = 0; i < N; i++) Pthread_join(tid[i], NULL); exit(0); } /* thread routine */ void *thread(void *vargp) { int myid = *((int *)vargp); printf("Hello from thread %d\n", myid); return NULL; } race.c

Race Elimination  Make sure don’t have unintended sharing of state /* a threaded program without the race */ int main() { pthread_t tid[N]; int i; for (i = 0; i < N; i++) { int *valp = malloc(sizeof(int)); *valp = i; Pthread_create(&tid[i], NULL, thread, valp); } for (i = 0; i < N; i++) Pthread_join(tid[i], NULL); exit(0); } /* thread routine */ void *thread(void *vargp) { int myid = *((int *)vargp); free(vargp); printf("Hello from thread %d\n", myid); return NULL; } norace.c

Today  Races  Deadlocks  Dining Philosopher's Problem  Condition Variable

Another Worry: Deadlock  Def: A process is deadlocked iff it is waiting for a condition that will never be true.  Typical Scenario  Processes 1 and 2 needs two resources (A and B) to proceed  Process 1 acquires A, waits for B  Process 2 acquires B, waits for A  Both will wait forever!  Analogous to a traffic gridlock

Deadlocking With Semaphores int main() { pthread_t tid[2]; Sem_init(&mutex[0], 0, 1); /* mutex[0] = 1 */ Sem_init(&mutex[1], 0, 1); /* mutex[1] = 1 */ Pthread_create(&tid[0], NULL, count, (void*) 0); Pthread_create(&tid[1], NULL, count, (void*) 1); Pthread_join(tid[0], NULL); Pthread_join(tid[1], NULL); printf("cnt=%d\n", cnt); exit(0); } void *count(void *vargp) { int i; int id = (int) vargp; for (i = 0; i < NITERS; i++) { P(&mutex[id]); P(&mutex[1-id]); cnt++; V(&mutex[id]); V(&mutex[1-id]); } return NULL; } Tid[0]: P(s 0 ); P(s 1 ); cnt++; V(s 0 ); V(s 1 ); Tid[1]: P(s 1 ); P(s 0 ); cnt++; V(s 1 ); V(s 0 );

Deadlock Visualized in Progress Graph Locking introduces the potential for deadlock: waiting for a condition that will never be true Any trajectory that enters the deadlock region will eventually reach the deadlock state, waiting for eithe r s 0 or s 1 to become nonzero Other trajectories luck out and s kirt the deadlock region Unfortunate fact: deadlock is of ten nondeterministic Thread 1 Thread 2 P(s 0 )V(s 0 )P(s 1 )V(s 1 ) P(s 1 ) P(s 0 ) V(s 0 ) Forbidden region for s 0 Forbidden region for s 1 Deadlock state Deadlock region s 0 =s 1 =1

Avoiding Deadlock int main() { pthread_t tid[2]; Sem_init(&mutex[0], 0, 1); /* mutex[0] = 1 */ Sem_init(&mutex[1], 0, 1); /* mutex[1] = 1 */ Pthread_create(&tid[0], NULL, count, (void*) 0); Pthread_create(&tid[1], NULL, count, (void*) 1); Pthread_join(tid[0], NULL); Pthread_join(tid[1], NULL); printf("cnt=%d\n", cnt); exit(0); } void *count(void *vargp) { int i; int id = (int) vargp; for (i = 0; i < NITERS; i++) { P(&mutex[0]); P(&mutex[1]); cnt++; V(&mutex[id]); V(&mutex[1-id]); } return NULL; } Tid[0]: P(s0); P(s1); cnt++; V(s0); V(s1); Tid[1]: P(s0); P(s1); cnt++; V(s1); V(s0); Acquire shared resources in same order

Avoided Deadlock in Progress Graph No way for trajectory to get stuck Processes acquire locks in same order Order in which locks released immaterial Thread 1 Thread 2 P(s 0 )V(s 0 )P(s 1 )V(s 1 ) P(s 1 ) P(s 0 ) V(s 0 ) Forbidden region for s 0 Forbidden region for s 1 s 0 =s 1 =1

Threads Summary  Threads provide another mechanism for writing concurrent programs  Threads are growing in popularity  Somewhat cheaper than processes  Easy to share data between threads  However, the ease of sharing has a cost:  Easy to introduce subtle synchronization errors  Tread carefully with threads!  For more info:  D. Butenhof, “Programming with Posix Threads”, Addison-Wesley, 1997

Dining Philosopher’s Problem (Dijkstra ’71) Philosophers eat/think Eating needs two forks Pick one fork at a time Captures the concept of multiple threads competing for shared resources

Dining Philosopher’s Problem  Thinking about philosophers makes it easier to think abstractly.  The philosophers are very logical  They want to settle on a shared policy that all can apply concurrently  They are hungry: we should let everyone eat (eventually)  The policy should be totally fair.  Design an algorithm that the philosophers can follow that insures that none starves as long as each philosopher eventually stops eating, and such that the maximum number of philosophers can eat at once.

Wrong design void philosopher() { while(1) { sleep(); get_left_fork(); get_right_fork(); eat(); put_left_fork(); put_right_fork(); } Other (inefficient) ideas: use a binary semaphore before getting the forks Recommended reading:

What can go wrong?  Starvation: Leaving some philosopher hungry (for a long time) in some situation  Deadlock: All the philosophers waits or gets “stuck”; nobody can make progress  Livelock: Everyone does something endlessly (e.g., infinite loop) without ever eating! Deadlock  Starvation but not vice versa

Solution 1: test (get_fork blocks until you can eat) #define N 5 /* Number of philosphers */ #define RIGHT(i) (((i)+1) %N) #define LEFT(i) (((i)==N) ? 0 : (i)+1) typedef enum { THINKING, HUNGRY, EATING } phil_state; phil_state state[N]; semaphore mutex =1; semaphore s[N]; /* one per philosopher, all 0 */ void test(int i) { if ( state[i] == HUNGRY && state[LEFT(i)] != EATING && state[RIGHT(i)] != EATING ) { state[i] = EATING; V(s[i]); } void get_forks(int i) { P(mutex); state[i] = HUNGRY; test(i); // try to acquire two forks V(mutex); P(s[i]); // wait if you can’t eat } void put_forks(int i) { P(mutex); state[i]= THINKING; test(LEFT(i)); // see if LEFT can eat test(RIGHT(i)); // see if RIGHT can eat V(mutex); } void philosopher(int process) { while(1) { think(); get_forks(process); eat(); put_forks(process); }

Solution 2 void get_forks(int i) { state[i] = HUNGRY; while ( state[i] == HUNGRY ) { P(mutex); if ( state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT(i)] != EATING ) { state[i] = EATING; V(s[i]); } V(mutex); P(s[i]); } void philosopher(int process) { while(1) { think(); get_forks(process); eat(); put_forks(); } void put_forks(int i) { P(mutex); state[i]= THINKING; if ( state[LEFT(i)] == HUNGRY ) V(s[LEFT(i)]); if ( state[RIGHT(i)] == HUNGRY) V(s[RIGHT(i)]); V(mutex); }

Today  Races  Deadlocks  Dining Philosopher's Problem  Condition Variable

Difficulties in using Semaphores  Semaphores provide a very general mechanism for synchronization.  The power of semaphores derives from calls to P() and V() that are unmatched.  E.g., reader/writer and dining phil.  Unlike mutex (locks) where we lock() and unlock()  This means that it’s very tricky to get it right (e.g., no single fixed pattern of use and/or more than one semaphores).

Condition Variables  Condition variables is a synchronization primitive that helps us model events (rather than resources in the case of semaphores).  A condition variable represents some condition that a thread can:  Wait on, until the condition occurs; or  Notify other waiting threads that the condition has occur  It provides a place to wait (queue).

Condition Variables  Operations on condition variables:  wait() -- Block until another thread calls signal() or broadcast() on the CV  signal() -- Wake up one thread waiting on the CV  broadcast() -- Wake up all threads waiting on the CV  Pthread  pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m);  pthread_cond_signal(pthread_cond_t *c);  pthread_cond_broadcast (pthread_cond_t *c);  Used with mutex

Broadcast  The pthread_cond_broadcast() function is used whenever the shared- variable state has been changed in a way that more than one thread can proceed with its task.  Single producer/multiple consumer problem  The producer would notify all consumers that might be waiting; more throughput on a multi-processor.  Read-write lock.  Wakes up all waiting readers when a writer releases its lock. Recommended reading

Producer and consumer  Important to use while statement to check the condition after waking up. It handles spurious wakeup. cond_t empty, fill; void produce(int item) { mutex_lock(&mutex); while (count == MAX) cond_wait(&empty, &mutex); put(item); // put an item in the circular buffer cond_signal(&fill); // signal an item is filled mutex_unlock(&mutex); } int consumer() { mutex_lock(&mutex); while (count == 0) cond_wait(&fill, &mutex); int item = get(); cond_signal(&empty); mutex_unlock(&mutex); return item; }

Next Lecture  So far we have learned basic concepts in Operating System.  This is not an OS class  But, most of you didn’t take OS.  We will begin to talk more about distributed systems.