Download presentation
Presentation is loading. Please wait.
Published bySydney Bates Modified over 6 years ago
1
Lecture 6 Interprocess Communication with Homework#2
Oct. 4, 2016 Kyu Ho Park
2
IPC Problems The 3 Issues of IPC 1. How one process can pass information to another. 2. How to make sure that two or more processes do not get into other’s way in competing to get a same resource Mutual Exclusion. 3. How to make proper sequencing when dependencies are present among processes such as producers and consumers Synchronization.
3
Interprocess Communication Race Conditions
Printer Buffer Slot no. Printing_slot Next_Free_slot Two processes want to access shared memory at same time
4
Race Conditions 1.Process_A is running: Read ‘next_free_slot’ Store ‘next_free_slot’ to save_slot 2.Process_A is switched to Process_B 3.Process_B is running: Write a file at the slot 7 4.Process_B is switched to Process_A 5.Process_A is running : Write a file to print at the slot 7 Out: indicates which file will be printed In: indicates which slot is free. Spooler: Simultaneous Peripheral Operation On Line
5
Race Conditions, Critical Section and Mutual Exclusion
Race conditions: Two or more processes are competing together to get certain shared resources. Critical Section: That part of the program where the shared memory is accessed. Mutual Exclusion : Making sure that if one process is using a shared resource the other processes will be excluded from doing the same thing.
6
Critical Sections Four conditions to provide mutual exclusion:
1. No two processes simultaneously in critical Section, 2. No assumptions made about speeds or numbers of CPUs, 3. No process running outside its critical section may block another process, 4. No process must wait forever to enter its critical section.
7
Mutual Exclusion with Busy-Waiting
Disabling Interrupts: The simplest solution is to have each process disable all interrupts just after entering its critical section and re-enable them just before leaving it. This approach is generally unattractive because it is unwise to give user processes the power to turn off interrupts. Suppose that one of them did it, and never turned them on again. ??? Disabling interrupts is often a useful technique within the OS but is not appropriate as a general mutual exclusion mechanism for user processes.
8
Mutual Exclusion by Busy-Waiting: Lock Variables
P1: P0: while (true){ acquire lock; critical section; release lock; remainder section; while (true){ acquire lock; critical section; release lock; remainder section; What will happen in this case?
9
Mutual Exclusion with Busy Waiting
Proposed solution to critical region problem (a) Process (b) Process 1.
10
Strict Alternation What will happen in this case?
//10min for execution //1 msec for execution P0: CS-> turn=1 -> NCS[10min] P1: busy-waiting CS->turn=0->NCS[1msec]->busy-waiting What will happen in this case? Spin lock: A lock that uses busy waiting.
11
TSL Instruction TSL RX, LOCK; Test & Set Lock It reads the contents of the memory word LOCK into register RX and then stores a nonzero value at the memory address LOCK. LOCK : shared variable When LOCK is 0, any process may set it to 1 using the TSL and read or write the shared memory. When it is done, the process sets LOCK back to 0.
12
Mutual Exclusion with Busy Waiting
Entering and leaving a critical region using the TSL instruction
13
Sleep and Wakeup The drawback of Busy-Waiting
H: Process with High Priority L: Process with Low Priority In case of the priority based scheduling, when H becomes ready to run when L is in CS, H now begins to run. What will happen? Priority Inversion !
14
Producer-Consumer Consumer Producer 1 2 .. …. N
Producer wants to put some items in the buffer but buffer is full, then the Producer goes to sleep until the Consumer removes one or more items and wakes up the producer. Consumer wants to get some items in the buffer but the buffer is empty, then the Consumer goes to sleep until the Producer puts one or more items in the buffer and wakes up the Consumer.
15
Sleep and Wakeup
16
Producer-Consumer Problem
Is there any racing problem in the previous Producer-Consumer problem? 1.Consumer reads count==0 2.Scheduler[Producer: running, Consumer: ready] 3.Producer inserts an item in the buffer, and ++count 4.Producer calls wakeup to wake the consumer up. 5.Consumer next runs, and goes to sleep(Why?). 6.Sooner or later the producer will fill up the buffer and also go to sleep. Both will sleep forever. Which one causes this problem and How to solve?
17
Semaphore( Edsger Dijkstra)
Synchronization tool that does not require busy-waiting. Semaphore S : integer variable. Two standard operations to modify S : They are all atomic action. acquire( ) { or down( )}// originally P( ) release( ) { or up( )} // originally V( ) P(S) : If S is greater than 0, decrement S. if S is zero, suspend execution of the process. V(S) : If some other process has been suspended waiting for S, Increment S. Wake it up. If no process is suspended waiting for S, increment S. // If S is 1 or 0, it is called a binary semaphore. // If S is declared as a positive integer, it is a counting semaphore.
18
Semaphore Checking the value, changing it, and possibly going to sleep, is all done as a single, invisible atomic action. This atomicity is absolutely essential to solving synchronization problems and avoiding race conditions. How can we implement down( ) and up( ) in indivisible way?
19
The producer-consumer problem using semaphores
20
Implementation of mutex_lock and mutex_unlock
Mutexes Implementation of mutex_lock and mutex_unlock
21
Classical IPC Problem: Dining Philosophers Problem[Dijkstra, 1965]
The life of a philosopher consists of alternate period eating and thinking. When a philosopher gets hungry, she tries to acquire her left and right fork, one at a time, in either order. If successful in acquiring two forks, she eats for a while, then puts down the forks, and continues to think. Question: Can you write a program for each philosopher that never gets stuck?
22
Classical IPC Problems Dining Philosophers (1)
Philosophers eat/think Eating needs 2 forks Pick one fork at a time How to prevent deadlock Deadlock:
23
The Deadlock Problem A set of blocked processes each holding a resource and waiting to acquire a resource held by another process in the set. Example System has 2 disk drives. P1 and P2 each hold one disk drive and each needs another one.
24
Bridge Crossing Example
Traffic only in one direction. Each section of a bridge can be viewed as a resource. If a deadlock occurs, it can be resolved if one car backs up (preempt resources and rollback). Several cars may have to be backed up if a deadlock occurs. Starvation is possible.
25
System Model Resource types R1, R2, . . ., Rm
CPU cycles, memory space, I/O devices Each resource type Ri has Wi instances. Each process utilizes a resource as follows: request use release
26
Deadlock Characterization
Deadlock can arise if four conditions hold simultaneously. Mutual exclusion: only one process at a time can use a resource. Hold and wait: a process holding at least one resource is waiting to acquire additional resources held by other processes. No preemption: a resource can be released only voluntarily by the process holding it, after that process has completed its task. Circular wait: there exists a set {P0, P1, …, P0} of waiting processes such that P0 is waiting for a resource that is held by P1, P1 is waiting for a resource that is held by P2, …, Pn–1 is waiting for a resource that is held by Pn, and P0 is waiting for a resource that is held by P0.
27
Dining Philosophers (2)
Any Problem?
28
Dining Philosophers (3)
Solution to dining philosophers problem (part 1)
29
Dining Philosophers (4)
Solution to dining philosophers problem (part 2)
30
Readers and Writers Problem [ Courtois, 1971]
The Dining Philosophers problem is useful for modeling processes that are competing for exclusive access to a limited number of resources. This Readers and Writers problem models access to a database ,for example, an airline reservation system with many competing processes wishing to read and write it.
31
The Readers and Writers Problem
A solution to the readers and writers problem
32
Sleeping Barber Problem
The barber shop has one barber, one barber chair, and n chairs for waiting customers. If there are no customers present, the barber sits down in barber chair and fall asleep as in the Fig. When a customer arrives, he has to wake up the sleeping barber. If additional customers arrive while the barber is cutting a customer’s hair, they either sit down if there are empty chairs or leave the shop if all chairs are full.
33
The Sleeping Barber Problem (1)
34
The Sleeping Barber Problem (2)
Solution to sleeping barber problem.
35
Homework #2 ‘Producer – Consumer’ and ‘Readers-Writers’ Programming with pthreads Oct. 4. 2016
36
semaphore #include <semaphore.h> int sem_init(sem_t *sem, int pshared, unsigned int value); - sem: points to a semaphore object, pshared: if 0, the semaphore is local to the current process, else the semaphore may be shared between processes(Linux does not support it). value: initial value of the semaphore. int sem_wait(sem_t *sem); -This function waits until the semaphore is nonzero, and decreases the value of semaphore by 1. int sem_post(sem_t *sem); -This function increases the value of the semaphore by 1. int sem_destroy(sem_t *sem);
37
Synchronization with semaphore
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <semaphore.h> void *thread_function(void *arg); sem_t bin_sem; #define WORK_SIZE 1024 char work_area[WORK_SIZE]; int main() { int res; pthread_t a_thread; void *thread_result; res = sem_init(&bin_sem, 0, 0); if (res != 0) { perror("Semaphore initialization failed"); exit(EXIT_FAILURE); } res = pthread_create(&a_thread, NULL, thread_function, NULL); perror("Thread creation failed"); printf("Input some text. Enter 'end' to finish\n"); while(strncmp("end", work_area, 3) != 0) { fgets(work_area, WORK_SIZE, stdin); sem_post(&bin_sem); } printf("\nWaiting for thread to finish...\n"); res = pthread_join(a_thread, &thread_result); if (res != 0) { perror("Thread join failed"); exit(EXIT_FAILURE); printf("Thread joined\n"); sem_destroy(&bin_sem); exit(EXIT_SUCCESS); void *thread_function(void *arg) { sem_wait(&bin_sem); printf("You input %d characters\n", strlen(work_area) -1); pthread_exit(NULL);
38
Producer-comsumer in pseudo-codes[Modern OS,Tanenbaum]
#define N 100 /*number of slots in the buffer */ typedef int semaphore; /*semaphores are a special kind of int */ semaphore mutex = 1; /*controls access to critical region */ semaphore empty = N; /*counts empty buffer slots */ semaphore full = 0; /*counts full buffer slots */ void producer(void) { int item; while(TRUE) { /*TRUE is the constant 1 */ item = produce_item(); /*generate something to put in buffer */ down(&empty); /*decrement empty count */ down(&mutex); /*enter critical region */ insert_item(item); /*put new item in buffer */ up(&mutex); /*leave critical region */ up(&full); /*increment count of full slots */ } void consumer(void) while(TRUE) { /*infinite loop */ done(&full); /*decrement full count */ done(&mutex); /*enter critical region */ item = remove_item(); /*take item from buffer */ up(&empty); /*increment count of empty slots */ consume_item(item); /*do something with the item*/
39
Producer-Consumer Consumer Producer 1 .. …. N-1 BufferSize=N
1 .. …. N-1 BufferSize=N count ; //number of items in the buffer
40
Skeleton of pro_con.c res=sem_init(&empty,0,100); if( res!=0){
#include <stdio.h> #include <pthread.h> #include <semaphore.h> #include <stdlib.h> void *producer(void *arg); void *consumer(void *arg); sem_t mutex; sem_t empty; sem_t full; int buffer[100]; int count=0; int main(void) { int i; pthread_t threads[2]; int res; res=sem_init(&mutex, 0,1); if( res !=0){ perror(“mutex_init failed.\n”); exit(1); } res=sem_init(&empty,0,100); if( res!=0){ perror(“empty_init failed.\n”); exit(1); } res=sem_init(&full, 0,0); perror(“full_init failed.\n”); pthread_create(&threads[0], NULL, producer,NULL); pthread_create(&threads[1], NULL, consumer, NULL); for(i=0; i<2; i++) pthread_join(threads[i], NULL); sem_destroy(&mutex); sem_destroy(&empty); sem_destroy(&full); return 0; Continued to next page.
41
Skeleton of pro_con.c Fill in this box
void *producer(void *arg) { int i; for( i=0; i<300; i++){ } void *consumer(void *arg) Fill in this box
42
Homework #2 Problem 1: Assume that there are one producer and one consumer, where each producer and consumer produces and consumes 100 items respectively. Complete the skeleton program shown in page 40 and 41. If necessary you may use your variables in the program. Problem 2: Assume that there are 2 producers each one produces items, and 2 consumers each one consumes 100 items. Make your program based on your program of problem 1.
43
Homework#2 Problem 3: Implement the ‘Readers and Writers Problem’ shown in page 33~35 of this lecture note using pthread semaphore. Assuming that (1)there are 3 readers and 3 writers, (2)the size of DB is only 1 byte, (3)Writer-1 writes 1, writer-2 writes 2 and writer-3 writes 3 every one second(use sleep(1)), (4)Readers read DB randomly.
44
Submission Contents Submission Source Code Report
Brief Explanation of your Source Code Final Screenshots Page Limit : about 5 pages (except figures) Submission Due Date : Oct. 17, PM 23:59 Delay Penalty 10%/day (AM 00:00) Kim Woo Joong [EE516 Home2] student_number.zip (various compression format is allowed)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.