Motivation for ‘and’ Syncronization *A = 1; *B = 1; Process 1Process 2Process 3 wait(&A);wait(&A);wait(&B); wait(&B); signal(&A); signal(&B); signal(&B);

Slides:



Advertisements
Similar presentations
Florida State UniversityCOP5570 – Advanced Unix Programming IPC mechanisms Pipes Sockets System V IPC –Message Queues –Semaphores –Shared Memory.
Advertisements

Introduction to Concurrency
Operating Systems Lecture 7.
Recitation By yzhuang, sseshadr. Agenda Debugging practices – GDB – Valgrind – Strace Errors and Wrappers – System call return values and wrappers – Uninitialization.
CSCC69: Operating Systems
Unix IPC and Synchronization. Pipes and FIFOs Pipe: a circular buffer of fixed size written by one process and read by another int pipe(int fildes[2])
Readers and Writers An introduction to the Linux programming interface for using UNIX semaphores.
XSI IPC Message Queues Semaphores Shared Memory. XSI IPC Each XSI IPC structure has two ways to identify it An internal (within the Kernel) non negative.
System V IPC (InterProcess Communication) Messages Queue, Shared Memory, and Semaphores.
Enforcing Mutual Exclusion, Semaphores. Four different approaches Hardware support Disable interrupts Special instructions Software-defined approaches.
Concurrency, Race Conditions, Mutual Exclusion, Semaphores, Monitors, Deadlocks Chapters 2 and 6 Tanenbaum’s Modern OS.
Critical Sections and Semaphores A critical section is code that contains access to shared resources that can accessed by multiple processes. Critical.
Critical Sections and Semaphores A critical section is code that contains access to shared resources that can accessed by multiple processes. Critical.
1 Tuesday, June 27, 2006 "If the 8086 architects had designed a car, they would have produced one with legs, to be compatible with the horse." - Anonymous.
5.6 Semaphores Semaphores –Software construct that can be used to enforce mutual exclusion –Contains a protected variable Can be accessed only via wait.
© 2006 RightNow Technologies, Inc. Tribute to Synchronization Jeff Elser December 11 th, 2006.
Rings This chapter demonstrates how processes can be formed into a ring using pipes for communication purposes.
Inter Process Communication:  It is an essential aspect of process management. By allowing processes to communicate with each other: 1.We can synchronize.
UNIX IPC CSE 121 Spring 2003 Keith Marzullo. CSE 121 Spring 2003Review of Concurrency2 Creating a UNIX process A process is created by making an exact.
Unix IPC Unix has three major IPC constructs to facilitate interaction between processes: Message Queues (this PowerPoint document) permit exchange of.
Semaphores Questions answered in this lecture: Why are semaphores necessary? How are semaphores used for mutual exclusion? How are semaphores used for.
The Programming Interface. Main Points Creating and managing processes – fork, exec, wait Performing I/O – open, read, write, close Communicating between.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Processes Tarek Abdelzaher Vikram Adve.
CS162B: Semaphores (and Shared Memory) Jacob T. Chan.
1 Chapter 6 Interprocess Communications. 2 Contents u Introduction u Universal IPC Facilities u System V IPC.
Inter-Process Communication Mechanisms CSE331 Operating Systems Design.
Thread Synchronization with Semaphores
S -1 Shared Memory. S -2 Motivation Shared memory allows two or more processes to share a given region of memory -- this is the fastest form of IPC because.
Process. Processes A process is an abstraction for sequence of operations that implement a computation/program. A process may be manipulated, suspended,
System V IPC Provides three mechanisms for InterProcess Communication (IPC) : Messages : exchange messages with any process or server. Semaphores : allow.
2.3 InterProcess Communication (IPC)
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 8: Opening Files and Starting Processes.
Florida State UniversityCOP5570 – Advanced Unix Programming Today’s topics System V Interprocess communication (IPC) mechanisms –Message Queues –Semaphores.
File IO and command line input CSE 2451 Rong Shi.
1 Semaphores Chapter 7 from Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date: January.
1 Shared Memory. 2  Introduction  Creating a Shared Memory Segment  Shared Memory Control  Shared Memory Operations  Using a File as Shared Memory.
Semaphores Creating and Accessing Semaphore Sets Semaphore Operations
IPC Programming. Process Model Processes can be organized into a parent-child hierarchy. Consider the following example code: /* */
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Processes and Threads.
2.3 interprocess communcation (IPC) (especially via shared memory & controlling access to it)
Operating System Concepts and Techniques Lecture 3 Process M. Naghibzadeh Reference M. Naghibzadeh, Operating System Concepts and Techniques, First ed.,
Inter Process Comunication in Linux by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Semaphores Chapter 7 from Inter-process Communications in Linux:
© 2006 RightNow Technologies, Inc. Synchronization September 15, 2006 These people do not actually work at RightNow.
Slide 9-1 Copyright © 2004 Pearson Education, Inc. Inter process Communication Mechanisms  Allow arbitrary processes to exchange data and synchronize.
Message Queues. Unix IPC Package ● Unix System V IPC package consists of three things – Messages – allows processes to send formatted data streams to.
PThread Synchronization. Thread Mechanisms Birrell identifies four mechanisms commonly used in threading systems –Thread creation –Mutual exclusion (mutex)
Shared Memory Dr. Yingwu Zhu. Overview System V shared memory Let multiple processes attach a segment of physical memory to their virtual address spaces,
S -1 Processes. S -2 wait and waitpid (11.2) Recall from a previous slide: pid_t wait( int *status ) wait() can: (a) block; (b) return with status; (c)
1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 7: POSIX Interprocess Communication (IPC)
Lecture 8 Pipe, Signal, Semaphore (Homework #3 included) Nov. 3, 2015 Kyu Ho Park.
Process Related System Calls By Neha Hulkoti & Kavya Bhat.
Case Study: Pthread Synchronization Dr. Yingwu Zhu.
Operating Systems Inter-Process Communication Shared Memory & Semaphores Moti Geva
Distributed and Parallel Processing George Wells.
OS Assignment 3.
Semaphores Synchronization tool (provided by the OS) that does not require busy waiting. Logically, a semaphore S is an integer variable that, apart from.
Chapter 5: Process Synchronization – Part II
Example questions… Can a shell kill itself? Can a shell within a shell kill the parent shell? What happens to background processes when you exit from.
Tarek Abdelzaher Vikram Adve Marco Caccamo
Unix IPC Unix has three major IPC constructs to facilitate interaction between processes: Message Queues (this PowerPoint document) permit exchange of.
Interprocess Communication-1
Message Queues.
PTHREADS AND SEMAPHORES
Synchronization Primitives – Semaphore and Mutex
CSE 451: Operating Systems Winter 2003 Lecture 4 Processes
| Website for Students | VTU -NOTES -Question Papers
CSE 451: Operating Systems Autumn 2004 Module 4 Processes
Synchronization.
Lab #9 Semaphores Operating System Lab.
Presentation transcript:

Motivation for ‘and’ Syncronization *A = 1; *B = 1; Process 1Process 2Process 3 wait(&A);wait(&A);wait(&B); wait(&B); signal(&A); signal(&B); signal(&B); signal(&A);

‘and’ Syncronization *A = 1; *B = 1; Process 1Process 2Process 3 wait(&A);wait(&A, &B);wait(&B); signal(&A); signal(&A, &B); signal(&B); wait(&A, &B) denotes simultaneous wait on A and B. The semaphores A and B are decremented only if both of them can decremented without blocking

‘and’ Syncronization Implementation wait – if ((ap->value > 0) && (bp->value > 0)) { (ap->value)--; (bp->value)--; } else if (ap->value <= 0) list> else list> signal – ap->value++; list to ready queue> bp->value++; list to ready queue>

Why Wake All Processes on Signal? Process 1 Process 2 Process 3 a1: wait(&A,&B); a2: wait(&B,&C); a3: signal(&B,&C); b1: b2: c1: signal(&A,&B); c2: signal(&B,&C); Assume a1 is executed followed by a2, the semaphore queues are: A: process 1 B: process 1, process 2 C: process 2 Then, if a3 is executed and the signal only wakes up the first process in each queue, the semaphore queues are: A: process 1 B: process 2 C: Now process 1 holds B while blocking on A. Process 2 cannot proceed until process 1 gets A. This defeats the purpose of ‘and’ synchronization

POSIX:XSI Semaphores POSIX:XSI semaphores are part of the general POSIX:XSI interprocess communication facility A POSIX:XSI semaphore is created by executing a semget system call The semget creats a semaphore data structure in the kernel and returns an integer handle to the semaphore Processes cannot access semaphore data structures directly – only through system calls Semaphore ids or handles are analogous to file descriptors

POSIX:SEM vs POSIX:XSI Semaphores POSIX:XSI data structures are created and kept in the kernel and are referenced through integer handles In POSIX:SEM, a program declares a variable of type sem_t and passes a pointer to that variable

Semaphore Sets A semaphore set is an array of semaphore elements A process can perform operations on the entire set in a single system call The internal representation of semaphore sets and semaphore elements is not directly accessible Each semaphore includes at least the following: –A nonnegative integer representing semaphore value –Process ID of the last process to manipulate the semaphore element –Number of processes waiting for the semaphore element to increase –Number of processes waiting for the semaphore element value to equal 0

Semaphore Sets (Cont) Semaphore operations allow a process to block until a semaphore element value is 0 or until it becomes positive Each element has two queues associated with it – a queue of processes waiting for the semaphore element value to increase and a queue of processes waiting for the value to equal 0

Semaphore Creation SYNOPSIS #include int semget (key_t key, int nsems, int semflg); POSIX:XSI

IPC_PRIVATE #include #include #include #include #include #define PERMS S_IRUSR|S_IWUSR #define SET_SIZE 3 int semid; void main(void) { int seimid; if ((semid = semget(IPC_PRIVATE, SET_SIZE, PERMS)) < 0) perror("Could not create new private semaphore"); else printf("Semaphore created with ID %d\n",semid); }

#include #include #include #include #include #include #define PERMS S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH #define SET_SIZE 1 #define KEY ((key_t)99887) void main(void) { int semid; if ((semid = semget(KEY, SET_SIZE, PERMS | IPC_CREAT)) < 0) fprintf(stderr, "Error creating semaphore with key %d: %s\n", (int)KEY, strerror(errno)); else printf("Semaphore with ID %d created for key %d\n",semid,(int)KEY); } Random Key

Generate Key from ftok int semid; key_t mykey; if (argc != 3) { fprintf(stderr, "Usage: %s filename id\n", argv[0]); exit(1); } if ((mykey = ftok(argv[1], atoi(argv[2]))) == (key_t) -1) { fprintf(stderr, "Could not derive key from filename %s: %s\n", argv[1], strerror(errno)); exit(1); } else if ((semid = semget(mykey, SET_SIZE, PERMS | IPC_CREAT)) < 0) { fprintf(stderr, "Error creating semaphore with key %d: %s\n", (int)mykey, strerror(errno)); exit(1);

semop SYNOPSIS #include int semop(int semid, struct sembuf *sops, int nsops); POSIX:XSI A process can increment, decrement or test individual semaphore elements with the semop system call semid is handle returned by semget sops points to an array of element operations nsops specifies the number of element operations in the sops array semop returns –1 and sets errno on error

struct sembuf struct sembuf has the following three fields short sem_num: The number of the semaphore element short sem_op: The particular operation to be performed on the semaphore element short sem_flg: The flags to specify options for the opration

sem_op If sem_op > 0, semop adds the value to the corresponding semaphore element and awakens processes waiting for semaphore element to increase If sem_op = 0, and semaphore element value is not 0, semop blocks the calling process (waiting for 0) and increments the count of processes waiting for a zero value of that element If sem_op < 0, semop adds the value to the corresponding semaphore element value provided the result would not be negative. If the operation would make the element value negative, semop blocks the process on the event that the semaphore element value increases. If the resulting value is 0, semop wakes the processes waiting for 0

set_sembuf_struct #include #include #include void set_sembuf_struct(struct sembuf *s, int num, int op, int flg) { s->sem_num = (short) num; s->sem_op = op; s->sem_flg = flg; return; } Do not set sembuf elements in a declaration such as: struct sembuf myopbuf = {1, –1, 0}

Semaphore – Example 1 struct sembuf GET_TAPES[2] struct sembuf RELEASE_TAPES[2] set_sembuf_struct(&(GET_TAPES[0]), 0,–1,0); set_sembuf_struct(&(GET_TAPES[1]), 1,–1,0); set_sembuf_struct(&(RELEASE_TAPES[0]), 0,1,0); set_sembuf_struct(&(RELEASE_TAPES[1]), 1,1,0); Process 1:semop(S, GET_TAPES,1); semop(S, RELEASE_TAPES,1); Process 2:semop(S,GET_TAPES,2); semop(S,RELEASE_TAPES,2); Process 3:semop(S, GET_TAPES + 1,1); semop(S, RELEASE_TAPES + 1,1);

struct sembuf – Example 1 GET_TAPES[0]RELEASE_TAPES[0]num = 0 op = –1 op = 1 flg = 0flg = 0 GET_TAPES[1]RELEASE_TAPES[1]num = 1 op = –1 op = 1flg = 0

Semaphore – Ex 2 (Top) … int semid; int semop_ret; struct sembuf semwait[1]; struct sembuf semsignal[1]; … if ( (argc != 2) || ((n = atoi (argv[1])) <= 0) ) { fprintf (stderr, "Usage: %s number_of_processes\n", argv[0]); exit(1); } /* Create a semaphore containing a single element */ if ((semid = semget(IPC_PRIVATE, SET_SIZE, PERMS)) == -1) { fprintf(stderr, "[%ld]: Could not access semaphore: %s\n", (long)getpid(), strerror(errno)); exit(1); }

Semaphore – Ex 2 (Upper Middle) /* Initialize the semaphore element to 1 */ set_sembuf_struct(semwait, 0, -1, 0); set_sembuf_struct(semsignal, 0, 1, 0); if (semop(semid, semsignal, 1) == -1) { fprintf(stderr, "[%ld]: semaphore increment failed - %s\n", (long)getpid(), strerror(errno)); if (remove_semaphore(semid) == -1) fprintf(stderr, "[%ld], could not delete semaphore - %s\n", (long)getpid(), strerror(errno)); exit(1); }

for (i = 1; i < n; ++i) if (childpid = fork()) break; /* Each child sends pid and ppid info to buffer */ while(( (semop_ret = semop(semid, semwait, 1)) == -1) && (errno == EINTR)) ; if (semop_ret == -1) fprintf(stderr, "[%ld]: semaphore decrement failed - %s\n", (long)getpid(), strerror(errno)); else { /* Each child prints out its pid and ppid buffer */ while(((semop_ret = semop(semid, semsignal, 1)) == -1) && (errno == EINTR)) ; if (semop_ret == -1) fprintf(stderr, "[%ld]: semaphore increment failed - %s\n", (long)getpid(), strerror(errno)); } Semaphore – Ex 2 (Lower Middle)

Semaphore – Ex 2 (Bottom) while((wait(&status) == -1) && (errno == EINTR)) ; if (i == 1) /* the original process removes the semaphore */ if (remove_semaphore(semid) == -1) fprintf(stderr, "[%ld], could not delete semaphore - %s\n", (long)getpid(), strerror(errno)); exit(0); }

Semaphore – Example 3 #include #define SET_SIZE 2 struct sembuf myop[SET_SIZE]; set_sembuf_struct(&(myop[0]), 0, 0, 0); set_sembuf_struct(&(myop[1]), 0, 1, 0); if (semop(semid, myop, 2) == -1) perror(“Semaphore operation failed”);

struct sembuf myop[0] num = 0 op = 0 flg = 0 myop[1] num = 0 op = 1 flg = 0

semctl #include int semctl(int semid, int semnum, int cmd, /* union semun arg */ semctl querries or sets the values of individual semaphore elements semid identifies the semaphore set semnum indicates the semaphore element within the set cmd refers to individual elements and specifies which command is to be executed arg is used differently for different cmd values

Important Commands GETVAL:Return the value of a specific semaphore element GETPID:Return process ID of last process to manipulate element GETNCNT: Return number of processes waiting for element to increment GETZCNT:Return number of processes waiting for element to become 0 SETVAL: Set value of a specific semaphore element to arg.val IPC_RMID:Remove the semaphore identified by semid IPC_SET:Set the permissions of the semaphore semctl returns –1 on error and and sets errno – On success the return value is 0 for all commands except GETVAL, GETPID, GETNCNT, and GETZCNT return the value of the command

semnum Paramater union semnum { int val; struct semid_ds *buf; short *array; }; May not be included directly in programs, since some systems do not define it in semaphore header files

… int initialize_sem_element(int semid, int semnum, int semvalue) { union semun arg; arg.val = semvalue; return semctl(semid, semnum, SETVAL, arg); } void main(void) { int semid; int retval; if ((semid = semget(IPC_PRIVATE, 2, 0600)) < 0) perror("Could not create new private semaphore"); retval = initialize_sem_element(semid,1,3); printf("initialize_sem_element returned %d\n",retval); } initialize_sem_element returns 0 on success and –1 and sets errno on error initialize _sem_element

remove_semaphore #include #include #include int remove_semaphore(int semid) { return semctl(semid, 0, IPC_RMID); }

Command Prompt Semaphore Ops List all semaphores:ipcs –s Remove semaphore id 12345:ipcrm 12345

#include #include #include #include int semop_restart(int semid, struct sembuf *sops, int nsops) { int retval; while ( ((retval = semop(semid, sops, nsops)) == -1) && (errno == EINTR) ) ; return retval; } semop_restart

sem_wait_restart #include #include int sem_wait_restart(sem_t *sem) { int retval; while ( ((retval = sem_wait(sem)) == -1) && (errno == EINTR) ) ; return retval; }