Thread Synchronization with Semaphores

Slides:



Advertisements
Similar presentations
CS Lecture 4 Programming with Posix Threads and Java Threads George Mason University Fall 2009.
Advertisements

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.
Threads Lab اللهم علمنا ما ينفعنا،،، وانفعنا بما علمتنا،،، وزدنا علماً
Concurrency, Race Conditions, Mutual Exclusion, Semaphores, Monitors, Deadlocks Chapters 2 and 6 Tanenbaum’s Modern OS.
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.
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);
Fork Fork is used to create a child process. Most network servers under Unix are written this way Concurrent server: parent accepts the connection, forks.
Threads 1 CS502 Spring 2006 Threads CS-502 Spring 2006.
Lecture 18 Threaded Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
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.
SMP threads an Introduction to Posix Threads. Technical Definition 1.Independent stream of instructions that can be scheduled to run by an operating system.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
Chapter 4: Threads Adapted to COP4610 by Robert van Engelen.
Netprog Threads Programming1 Threads Programming Refs: Chapter 23.
CS162B: Semaphores (and Shared Memory) Jacob T. Chan.
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.
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.
10/16/ Realizing Concurrency using the thread model B. Ramamurthy.
System V IPC Provides three mechanisms for InterProcess Communication (IPC) : Messages : exchange messages with any process or server. Semaphores : allow.
1 Confidential Enterprise Solutions Group Process and Threads.
Today’s topic Pthread Some materials and figures are obtained from the POSIX threads Programming tutorial at
B. RAMAMURTHY 10/24/ Realizing Concurrency using the thread model.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
1 Semaphores Chapter 7 from Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date: January.
Source: Operating System Concepts by Silberschatz, Galvin and Gagne.
Semaphores Creating and Accessing Semaphore Sets Semaphore Operations
Pthreads: A shared memory programming model
Threads CSCE Thread Motivation Processes are expensive to create. Context switch between processes is expensive Communication between processes.
S -1 Posix Threads. S -2 Thread Concepts Threads are "lightweight processes" –10 to 100 times faster than fork() Threads share: –process instructions,
Threads and Locking Ioctl operations. Threads Lightweight processes What’s wrong with processes? –fork() is expensive – 10 to 100 times slower –Inter.
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
UNIX Socket Programming CS 6378 Project Reference Book: Unix Network programming: Networking APIs: Sockets and XTI (2nd edition), Prentice Hall >> Threads.
Pthreads.
2.3 interprocess communcation (IPC) (especially via shared memory & controlling access to it)
Silberschatz, Galvin and Gagne  2002 Modified for CSCI 399, Royden, Operating System Concepts Operating Systems Lecture 14 Threads 2 Read Ch.
Inter Process Comunication in Linux by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Unix System Calls and Posix Threads.
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.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
Threads A thread is an alternative model of program execution
NCHU System & Network Lab Lab #6 Thread Management Operating System Lab.
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
7/9/ Realizing Concurrency using Posix Threads (pthreads) B. Ramamurthy.
Tutorial 4. In this tutorial session we’ll see Threads.
A thread is a basic unit of CPU utilization within a process Each thread has its own – thread ID – program counter – register set – stack It shares the.
Distributed and Parallel Processing George Wells.
CS 537 – Introduction to Operating Systems
Threads Some of these slides were originally made by Dr. Roger deBry. They include text, figures, and information from this class’s textbook, Operating.
Realizing Concurrency using the thread model
Threads Threads.
Boost String API & Threads
Copyright ©: Nahrstedt, Angrave, Abdelzaher
Linux Processes & Threads
Realizing Concurrency using Posix Threads (pthreads)
Operating Systems Lecture 13.
Realizing Concurrency using the thread model
PTHREADS AND SEMAPHORES
Operating System Concepts
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
| Website for Students | VTU -NOTES -Question Papers
Tutorial 4.
POSIX Threads(pthreads)
Presentation transcript:

Thread Synchronization with Semaphores Lab 8 CIS 370 UMass Dartmouth

Threads Threads allow parallel execution of processes or distinct parts of a single process. All threads within a process share: The same address space Process instructions Most data Open files (descriptors) Signals and signal handlers Current working directory User and group id

Threads Each thread has a unique: Basic thread operations: Thread ID (tid) Set of registers, stack pointer Stack for local variables, return addresses Signal mask Priority Return value: errno Basic thread operations: Creation Termination Joining Synchronization

Threads

POSIX Threads (Pthreads) In Linux, threads are handled with the Pthreads API. #include <pthread.h> pthread_t tid; //Thread Identifier pthread_attr_t attr; //Set of attributes for a thread A thread can get its own thread identifier using: pthread_t pthread_self(); Attributes can be initialized using: int pthread_attr_init(&attr);

Pthreads - Creation Returns 0 on success, or error on failure. int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*thread_func)(void*), void *arg); Returns 0 on success, or error on failure. thread is a pointer to the created thread. attr is a pointer to a set of thread attributes. If attr is NULL, default attributes are used. thread_func is the first function a newly created thread will execute. arg is the only parameter to thread_func.

Pthreads - Joining Returns 0 on success, or error on failure. int pthread_join(pthread_t thread, void **value_ptr); Returns 0 on success, or error on failure. thread is an executing thread. value_ptr contains the value of the target thread’s exit parameter. A call to join() will suspend the calling thread until the target thread terminates.

Pthreads - Termination void pthread_exit(void *value_ptr); Never returns. value_ptr is the thread’s exit parameter. A call to pthread_exit() will terminate the calling process and send a reference to value_ptr to any joining thread.

Pthreads - Example Output: Child Thread: Value = 5 Parent Thread: Value = 15

Pthreads - Example

Pthreads – Another Example

Pthreads – Another Example Actual Output: Run1: Value = 1,090,299 Run2: Value = 1,002,569 Run3: Value = 1,003,650 Run4: Value = 1,806,077 Run5: Value = 1,010,439 Run6: Value = 1,243,521 Run7: Value = 1,455,218 Expected Output: Value = 2,000,000

Pthreads – Another Example If this code is executed serially (Thread 1, followed by Thread 2) there are no problems. However threads execute in an arbitrary order. Consider the following execution scenario: Thread 1 Thread 2 Value tmp = value --- tmp = tmp + 1 value = tmp 1

Pthreads – Another Example The problem is caused by allowing multiple threads to operate on the same data simultaneously. Solution: provide functions that will block one thread if another thread is trying to access data that it is currently using. Pthreads may use semaphores to achieve this.

Semaphores Concept introduced by E.W. Dijkstra as a solution to process synchronization. A Semaphore can be viewed as an integer variable on which the following operations are allowed: Wait() Signal() In order to provide mutual exclusion: wait(semaphore) // Critical section signal(semaphore)

Semaphores Given a Semaphore sem, we’ll define the wait() and signal() operations as follows. wait(sem) if(sem != 0) decrement sem by one else wait until sem becomes non-zero, then decrement signal(sem) increment sem by one if (queue of waiting processes/threads is not empty) restart the first process/thread in wait queue

Semaphores To use Semaphores in UNIX: #include <sys/sem.h> UNIX semaphore operations are geared to work on sets of semaphores, rather than single objects. As a result, most semaphore routines are fairly complicated

Semaphores Associated with each semaphore in the set: semval – The semaphore value 0 or a positive integer sempid – The pid of the process that last acted on the semaphore semcnt – Number of processes waiting for the semaphore to reach a value greater than its current value semzcnt – Number of processes waiting for the semaphore to reach the value zero.

Get/create semaphore set – semget() int semget(key_t key, int nsems, int permflags); returns the semaphore set ID on success, or -1 on failure. key is a system-wide unique identifier describing the semaphore you want to connect to (or create). nsems gives the number of semaphores required in the semaphore set. permflags tells semget() what to do with the semaphore in question. IPC_CREAT: Create the semaphore if it doesn't already exist in the kernel.  IPC_EXCL: When used with IPC_CREAT, fail if semaphore already exists.

Control semaphore set – semctl() int semctl(int semid, int sem_num, int command, union semun ctl_arg); semid is a valid semaphore identifier, returned by a previous call to semget(). sem_num identifies a particular semaphore from the set. The first semaphore in a set is numbered 0. command controls the behavior of semctl(). ctl_arg is a union defined as: union semun{ int val; struct semid_ds *buf; unsigned short *array; };

Standard IPC functions More about the command parameter: Standard IPC functions IPC_STAT IPC_SET IPC_RMID Place status info into ctl_arg.buf Set ownerships/permissions from ctl_arg.buf Remove semaphore set from system Single semaphore operations GETVAL SETVAL GETPID GETNCNT GETZCNT Return value of semaphore (semval) Set value of semaphore to ctl_arg.val Return value of sempid Return semcnt Return semzcnt All semaphore (set) operations GETALL SETALL Place all semvals into ctl_arg.array Set all semvals according to ctl_arg.array

Semaphore Initialization Example One important use of semctl() is to set the initial values of semaphores, since semget() does not allow a process to do this.

Semaphore Initialization Example

Semaphores – semop() int semop(int semid, struct sembuf *op_array, size_t num_ops); This call actually performs fundamental semaphore operations. If unsuccessful, -1 is returned. semid is a valid semaphore identifier, returned by a previous call to semget(). op_array is an array of sembuf structures, defined in <sys/sem.h>. num_ops is the number of sembuf structures in the array. struct sembuf{ unsigned short sem_num; //index in semaphore set short sem_op; //tells semop() what to do short sem_flg; //options };

Case 1: sem_op value negative More about the sem_op parameter: Case 1: sem_op value negative This is basically the semaphore wait() operation. If the semaphore’s semval is ≥ |sem_op|, decrement semval by |sem_op|, otherwise wait until semval ≥ |sem_op|. *If sem_flg is set to IPC_NOWAIT, semop() will return an error. Case 2: sem_op value positive This is basically the semaphore signal() operation. The value of sem_op is simply added to the corresponding semval. Processes waiting on the new value of the semaphore will be woken up. Case 3: sem_op value zero In this case semop() will wait until the semaphore value is zero, but doesn’t alter semval. *If sem_flg is set to IPC_NOWAIT, and semval is not already zero, semop() will return an error immediately.

Ex: gcc –o lab8 lab8_template.c -lpthread Assignment In this lab, you will experiment with Linux Semaphores to provide mutual exclusion between threads trying to access a critical section of code. You will first have to implement the Semaphore wait() and signal() functions using the UNIX Semaphore procedures described in these slides. Download the template code and modify it to include various Semaphore operations which will ensure that the threads will always increment the critical_value variable to 2,000,000. www.cis.umassd.edu/~jplante/cis370/lab08/lab8_template.c To compile C code implementing Threads, you will need to append “-lpthread” in the terminal. Ex: gcc –o lab8 lab8_template.c -lpthread