Synchronization.

Slides:



Advertisements
Similar presentations
Threads Relation to processes Threads exist as subsets of processes Threads share memory and state information within a process Switching between threads.
Advertisements

CS Lecture 4 Programming with Posix Threads and Java Threads George Mason University Fall 2009.
Enforcing Mutual Exclusion, Semaphores. Four different approaches Hardware support Disable interrupts Special instructions Software-defined approaches.
Critical Sections and Semaphores A critical section is code that contains access to shared resources that can accessed by multiple processes. Critical.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
CS 241 Section Week #4 (2/19/09). Topics This Section  SMP2 Review  SMP3 Forward  Semaphores  Problems  Recap of Classical Synchronization Problems.
Introduction to Pthreads. Pthreads Pthreads is a POSIX standard for describing a thread model, it specifies the API and the semantics of the calls. Model.
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.
Copyright ©: University of Illinois CS 241 Staff1 Synchronization and Semaphores.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
What is a thread? process: an address space with 1 or more threads executing within that address space, and the required system resources for those threads.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Semaphore and Mutex Operations.
Programming with POSIX* Threads Intel Software College.
Linux Programming –Threads CS Threads Review Threads in the same address space –share everything in the address space –lighter than process –no.
File IO and command line input CSE 2451 Rong Shi.
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
Thread API Xiaohua Lu Office : CS 3310 Tel. : Office hours: 11-12,3-5 T,TR.
Synchronizing Threads with Semaphores
Pthreads.
Lecture 15 Semaphore & Bugs. Concurrency Threads Locks Condition Variables Fixing atomicity violations and order violations.
2.3 interprocess communcation (IPC) (especially via shared memory & controlling access to it)
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 11: Thread-safe Data Structures, Semaphores.
Pthreads #include pthread_t tid ; //thread id. pthread_attr_t attr ; void *sleeping(void *); /* thread routine */ main() { int time = 2 ; pthread_create(&tid,
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 12: Thread-safe Data Structures, Semaphores.
PThread Synchronization. Thread Mechanisms Birrell identifies four mechanisms commonly used in threading systems –Thread creation –Mutual exclusion (mutex)
Working with Pthreads. Operations on Threads int pthread_create (pthread_t *thread, const pthread_attr_t *attr, void * (*routine)(void*), void* arg) Creates.
Web Server Architecture Client Main Thread for(j=0;j
1 CMSC Laundry List P/W/F, Exam, etc. Instructors: HSG, HH, MW.
CS 311/350/550 Semaphores. Semaphores – General Idea Allows two or more concurrent threads to coordinate through signaling/waiting Has four main operations.
Case Study: Pthread Synchronization Dr. Yingwu Zhu.
CSC Advanced Unix Programming, Fall, 2008 Monday, December 1 Thread local storage, POSIX:SEM semaphores and POSIX:XSI IPC.
Chien-Chung Shen CIS/UD
Synchronization and Semaphores
CS 537 – Introduction to Operating Systems
C Threads and Semaphores
Lecture 6 Interprocess Communication with Homework#2
Semaphores Reference text: Tanenbaum ch
Synchronization: Basics
Instructors: Randal E. Bryant and David R. O’Hallaron
Process Synchronization
סמפורים.
Threads in C Caryl Rahn.
Pthreads – Create and Join
Threads Threads.
Copyright ©: Nahrstedt, Angrave, Abdelzaher
September 4, 1997 Parallel Processing (CS 667) Lecture 5: Shared Memory Parallel Programming with OpenMP* Jeremy R. Johnson Parallel Processing.
FILE LOCK #include <stdio.h> #include <stdlib.h>
POSIX Threads 1. Background 2. Threads vs. Processes
Operating Systems Lecture 13.
Instructor: Randy Bryant
Concurrent Programming
Thread Implementations; MUTEX
Synchronization and Semaphores
Operating System Concepts
Programming with Shared Memory
Jonathan Walpole Computer Science Portland State University
Synchronization Primitives – Semaphore and Mutex
Thread Implementations; MUTEX
Synchronization: Basics CSCI 380: Operating Systems
Programming with Shared Memory
Shared Memory Programming via Posix threads
Synchronization.
Outline Chapter 3: Processes Chapter 4: Threads So far - Next -
Semaphores Reference text: Tanenbaum ch
Lecture 12 CV and Semaphores
Instructor: Brian Railing
POSIX Threads(pthreads)
Lab #9 Semaphores Operating System Lab.
Presentation transcript:

Synchronization

Implementation of Semaphores in POSIX POSIX:SEM semaphore is variable of type sem_t Atomic Operations: int sem_init(sem_t *sem, int pshared, unsigned value); int sem_destroy(sem_t *sem); int sem_post(sem_t *sem); Int sem_trywait(sem_t *sem); Int sem_wait(sem_t *sem); Use <semaphore.h>

Unnamed Semaphores Ch 14 pp 491-501 #include <semaphore.h> Sem_t sem; You cannot make a copy of a semaphore variable!!! #include <semaphore.h> int sem_init(sem_t *sem, int pshared, unsigned value); pshared == 0: only threads of process creating semaphore can use semaphore.

Sharing Semaphores Sharing semaphores between threads within a process is easy, use pshared==0 Forking a process creates copies of any semaphore it has… this does not share the semaphore Making pshared non zero allows any process that can access the semaphore to use it. This places the semaphore in global environment.

sem_init can fail!!! In unsuccessful, sem_init returns -1 and sets errno. Example: sem_t semA; if (sem_init(&semA, 0, 1) == -1) perror(“Failed to initialize semaphore semA”); Value > sem_value_max Resources exhausted Insufficient privileges EINVAL ENOSPC EPERM cause errno

Semaphore Operations #include <semaphore.h> int sem_destroy(sem_t *sem); Destroying a semaphore that’s been destroyed gives undefined result. Destroying a semaphore on which a thread is blocked gives undefined results.

Semaphore Operations #include <semaphore.h> int sem_post(sem_t *sem); Unlocks the semaphore. If the semaphore value resulting from this operation is: positive, then no threads were blocked waiting for the semaphore. zero, then one of the threads blocked waiting for the semaphore will be allowed to return successfully from its call to sem_wait(). if unsuccessful, returns -1 and sets errno errno == EINVAL if semaphore doesnt exist

Semaphore Operations int sem_trywait(sem_t *sem); locks the semaphore if it is currently not locked (>0). doesn’t block returns -1 and errno==EAGAIN if semaphore zero can be interrupted by signal – errno == EINTR int sem_wait(sem_t *sem); locks the semaphore. If the semaphore value is currently zero, then the calling thread will block. Can be interrupted by signal – errno == EINTR

Example 1 on Semaphore (RR: 497) We want a shared variable ‘shared’ (critical section) to be protected by semaphore to allow for two functions getshared – is a function that returns the current value of the shared variable ‘shared’ incshared – is a function that that atomically increments the ‘shared’ variable.

Example, creating shared variable #include <errno.h> #include <semaphore.h> static int shared = 0; static sem_t sharedsem; int initshared(int val) { if (sem_init(&sharedsem, 0, 1) == -1) return -1; shared = val; return 0; }

Example – shared variable int getshared(int *sval) { while (sem_wait(&sharedsem) == -1) if (errno != EINTR) return -1; *sval = shared; return sem_post(&sharedsem); } int incshared() { shared++;

Example 2 on Semaphore (RR:500) A program to generate a set of threads and each thread writes to standard error Standard error (stderr) is a shared resource, hence if a thread outputs an informative message to standard error one character at the time, it becomes a critical region and we must protect it.

Thread with Critical Section (Example RR:500) - #include <errno.h> #include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <unistd.h> #define TEN_MILLION 10000000L #define BUFSIZE 1024

Thread with Critical Section void *threadout(void *args) { char buffer[BUFSIZE]; char *c; sem_t *semlockp; struct timespec sleeptime; semlockp = (sem_t *)args; sleeptime.tv_sec = 0; sleeptime.tv_nsec = TEN_MILLION; snprintf(buffer, BUFSIZE, "This is a thread from process %ld\n", (long) getpid()); c = buffer;

Thread with Critical Section /****************** entry section *************************/ while (sem_wait(semlockp) == -1) /* Entry section */ if(errno != EINTR) { fprintf(stderr, "Thread failed to lock semaphore\n"); return NULL; } /****************** start of critical section ***********/ while (*c != '\0') { fputc(*c, stderr); c++; nanosleep(&sleeptime, NULL); /****************** exit section ******************/ if (sem_post(semlockp) == -1) /* Exit section */ fprintf(stderr, "Thread failed to unlock semaphore\n"); /****************** remainder section ****************/ return NULL; }

Main program (Example RR:501) #include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <string.h> void *threadout(void *args); int main(int argc, char *argv[]) { int error; int i; int n; sem_t semlock; pthread_t *tids;

Main program (Example RR:501) if (argc != 2){/* check for valid number of command-line arguments */ fprintf (stderr, "Usage: %s numthreads\n", argv[0]); return 1; } n = atoi(argv[1]); tids = (pthread_t *)calloc(n, sizeof(pthread_t)); if (tids == NULL) { perror("Failed to allocate memory for thread IDs"); if (sem_init(&semlock, 0, 1) == -1) { perror("Failed to initialize semaphore");

Main program for (i = 0; i < n; i++) if (error = pthread_create(tids + i, NULL, threadout, &semlock)) { fprintf(stderr, "Failed to create thread:%s\n", strerror(error)); return 1; } if (error = pthread_join(tids[i], NULL)) { fprintf(stderr, "Failed to join thread:%s\n", return 0; }