CSC 1600: Chapter 6. Synchronizing Threads. Semaphores " Review: Multi-Threaded Processes"

Similar documents
Introduction to Threads

Synchronization: Basics

Synchronization: Basics

Carnegie Mellon. Bryant and O Hallaron, Computer Systems: A Programmer s Perspective, Third Edition

Programming with Threads Dec 7, 2009"

Carnegie Mellon Concurrency and Synchronization

Today. Threads review Sharing Mutual exclusion Semaphores

Synchronization: Advanced

Shared Variables in Threaded C Programs. Systemprogrammering Föreläsning 11 Programming with Threads

Process Synchronization: Semaphores. CSSE 332 Operating Systems Rose-Hulman Institute of Technology

Achieving Synchronization or How to Build a Semaphore

CS 550 Operating Systems Spring Concurrency Semaphores, Condition Variables, Producer Consumer Problem

Process Synchronisation (contd.) Operating Systems. Autumn CS4023

Pre-lab #2 tutorial. ECE 254 Operating Systems and Systems Programming. May 24, 2012

for (i = 0; i < 2; i++)

! What is the memory model for threads? ! How are variables mapped to memory instances? ! How many threads reference each of these instances?

Synchronization April 29, 2008

Week 3. Locks & Semaphores

Interprocess Communication and Synchronization

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017

Process Synchroniza/on

Chapter 7: Process Synchronization!

Lecture Topics. Announcements. Today: Concurrency (Stallings, chapter , 5.7) Next: Exam #1. Self-Study Exercise #5. Project #3 (due 9/28)

Multithreading Programming II

KING FAHD UNIVERSITY OF PETROLEUM & MINERALS. Information and Computer Science Department. ICS 431 Operating Systems. Lab # 9.

Chapter 6: Process Synchronization

Lecture Topics. Announcements. Today: Concurrency: Mutual Exclusion (Stallings, chapter , 5.7)

Carnegie Mellon. Synchroniza+on : Introduc+on to Computer Systems Recita+on 14: November 25, Pra+k Shah (pcshah) Sec+on C

MS Windows Concurrency Mechanisms Prepared By SUFIAN MUSSQAA AL-MAJMAIE

What is the Race Condition? And what is its solution? What is a critical section? And what is the critical section problem?

Process Synchronization. studykorner.org

Chapter 5 Concurrency: Mutual Exclusion. and. Synchronization. Operating Systems: Internals. and. Design Principles

POSIX Semaphores. Operations on semaphores (taken from the Linux man page)

CS420: Operating Systems. Process Synchronization

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017

Chapter 5: Process Synchronization. Operating System Concepts Essentials 2 nd Edition

Chapter 6: Synchronization. Operating System Concepts 8 th Edition,

Chapter 6: Process Synchronization. Operating System Concepts 8 th Edition,

Sistemi in tempo reale Anno accademico

Process Synchronization

CS3733: Operating Systems

Lecture 6. Process Synchronization

Sistemi in tempo reale

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition

Chapter 6: Process Synchronization

CS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization

CSC501 Operating Systems Principles. Process Synchronization

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy

CSC Systems Programming Fall Lecture - XIV Concurrent Programming. Tevfik Ko!ar. Louisiana State University. November 2nd, 2010

Synchronization Principles

Synchronization Spinlocks - Semaphores

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Lecture #24 Synchronization

Programming in Parallel COMP755

Chapter 6: Synchronization. Chapter 6: Synchronization. 6.1 Background. Part Three - Process Coordination. Consumer. Producer. 6.

Synchronization Primitives

Semaphore. Originally called P() and V() wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++; }

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition

CS533 Concepts of Operating Systems. Jonathan Walpole

Process Synchronization

Concurrency: a crash course

Concurrent Server Design Multiple- vs. Single-Thread

Outline. CS4254 Computer Network Architecture and Programming. Introduction 2/4. Introduction 1/4. Dr. Ayman A. Abdel-Hamid.

ENGR 3950U / CSCI 3020U UOIT, Fall 2012 Quiz on Process Synchronization SOLUTIONS

The course that gives CMU its Zip! Concurrency I: Threads April 10, 2001

Concurrent Processes Rab Nawaz Jadoon

Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective?

Process Synchronization

Synchronization I. Jo, Heeseung

CS 5523 Operating Systems: Midterm II - reivew Instructor: Dr. Tongping Liu Department Computer Science The University of Texas at San Antonio

Programming with Threads

CS 333 Introduction to Operating Systems Class 4 Concurrent Programming and Synchronization Primitives

IV. Process Synchronisation

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Lesson 6: Process Synchronization

Synchronization. Race Condition. The Critical-Section Problem Solution. The Synchronization Problem. Typical Process P i. Peterson s Solution

Lecture. DM510 - Operating Systems, Weekly Notes, Week 11/12, 2018

IT 540 Operating Systems ECE519 Advanced Operating Systems

Concurrency. Chapter 5

PESIT Bangalore South Campus

Process Synchronization

Dealing with Issues for Interprocess Communication

Synchronization I. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Concurrency Control. Synchronization. Brief Preview of Scheduling. Motivating Example. Motivating Example (Cont d) Interleaved Schedules

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Global Environment Model

CROWDMARK. Examination Midterm. Spring 2017 CS 350. Closed Book. Page 1 of 30. University of Waterloo CS350 Midterm Examination.

Process Synchronization

CS 470 Spring Mike Lam, Professor. Semaphores and Conditions

CONCURRENCY:MUTUAL EXCLUSION AND SYNCHRONIZATION

Concurrency, Mutual Exclusion and Synchronization C H A P T E R 5

2.c Concurrency Mutual exclusion & synchronization mutexes. Unbounded buffer, 1 producer, N consumers

Chapter 5 Concurrency: Mutual Exclusion and Synchronization

CS370 Operating Systems

Parallel Programming Languages COMP360

POSIX / System Programming

Mutual Exclusion and Synchronization

CS510 Operating System Foundations. Jonathan Walpole

Midterm Exam. October 20th, Thursday NSC

Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective?

Transcription:

CSC 1600: Chapter 6 Synchronizing Threads with Semaphores " Review: Multi-Threaded Processes" 1

badcnt.c: An Incorrect Program" #define NITERS 1000000 unsigned int cnt = 0; /* shared */ int main() pthread_t tid1, tid2; pthread_create(&tid1, NULL, Count, NULL); pthread_create(&tid2, NULL, Count, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); /* thread routine */ void * Count(void *arg) for (i=0; i<niters; i++) cnt++; linux>./badcnt BOOM! cnt=1988411 linux>./badcnt BOOM! cnt=1982618 if (cnt!= (unsigned)niters*2) printf("boom! cnt=%d\n", cnt); else printf("ok cnt=%d\n", cnt); pthread_exit(null); linux>./badcnt BOOM! cnt=1982696 cnt should be! equal to 2,000,000.! What went wrong?!! " Review: Race Conditions" Assume that two threads execute concurrently" " "cnt++; "/* cnt is global shared data */" One possible interleaving of statements is:" R1 = cnt R1 = R1 + 1 <timer interrupt! > R2 = cnt R2 = R2 + 1 cnt = R2 <timer interrupt!> cnt = R1 Race condition: The situation where several threads access shared data concurrently. The final value of the shared data may vary from one execution to the next. Then cnt ends up incremented once only! " 2

Race conditions" A race occurs when the correctness of the program depends on one thread reaching a particular statement before another thread." No races should occur in a program." Review: Critical Sections" Blocks of code that access shared data:" /* thread routine */ void * count(void *arg) for (i=0; i<niters; i++) cnt++; Threads must have mutual exclusive access to critical sections: two threads cannot simultaneously execute cnt++" 3

The Critical-Section Problem q Critical section (CS): block of code that uses shared data q CS problem: correctness of the program should not depend on one thread reaching point x before another thread reaches point y. q CS solution: allow a single thread in the CS at one time while(1) entry section Critical Section (CS) exit section Thread T i Remainder Section (RS) while(1) Thread T 1 entry section Critical Section (CS) exit section Remainder Section (RS) while(1) Thread T 2 entry section Critical Section (CS) exit section Remainder Section (RS) 4

Solving the CS Problem - Semaphores (1)" A semaphore is a synchronization tool provided by the operating system." A semaphore S can be viewed as an integer variable that can be accessed through 2 atomic operations:" " DOWN(S) also called wait(s) UP(S) also called signal(s) " Atomic means indivisible." When a thread has to wait, put it in a queue of blocked threads waiting on the semaphore." Semaphores (2)" In fact, a semaphore is a structure: " " struct Semaphore int count; Thread * queue; /* blocked */ ; /* threads */ struct Semaphore S; S.count must be initialized to a nonnegative value (depending on application)" 5

OS Semaphores - DOWN(S) or wait(s)" When a process must wait for a semaphore S, it is blocked and put on the semaphore s queue" DOWN(S):!!! <disable interrupts> S.count--; if (S.count < 0) block this thread place this thread in S.queue!!! <enable interrupts> Threads waiting on a semaphore S:" S.queue T3 T1 T5 OS Semaphores - UP(S) or signal(s)" The UP or signal operation removes one thread from the queue and puts it in the list of ready threads UP(S):!!! <disable interrupts> S.count++; if (S.count <= 0) remove a thread T from S.queue place this thread T on Ready list!!! <enable interrupts> S.queue T3 T1 T5 Ready queue T7 UP(S) 6

OS Semaphores - Observations" When S.count >= 0" - the number of threads that can execute wait(s) without being blocked is equal to S.count When S.count < 0" - the number of threads waiting on S is equal to S.count Atomicity and mutual exclusion" - no 2 threads can be in wait(s) and signal(s) (on the same S) at the same time" - hence the blocks of code defining wait(s) and signal(s) are, in fact, critical sections" Using Semaphores to Solve CS Problems" Thread Ti: DOWN(S); <critical section CS> UP(S); <remaining section RS> To allow only one thread in the CS (mutual exclusion):" - initialize S.count to " What should be the value of S to allow k threads in CS? " - initialize S.count to " 7

Solving the Earlier Problem" /* Thread T1 routine */ void * count(void *arg) for (i=0; i<10; i++) cnt++; /* Thread T2 routine */ void * count(void *arg) for (i=0; i<10; i++) cnt++; Solution: use Semaphores to impose mutual exclusion to executing cnt++" How are Races Prevented? " Semaphore mutex; 1 /* Thread T1 routine */ void * count(void *arg) /* Thread T2 routine */ void * count(void *arg) for (i=0; i<10; i++ for (i=0; i<10; i++) DOWN(mutex); DOWN(mutex); R1 ß cnt R1 ß R1+1 cnt ß R1 R2 ß cnt R2 ß R2+1 cnt ß R2 UP(mutex); UP(mutex); 8

Solving the Earlier Problem" Semaphore mutex; 1 /* Thread T1 routine */ void * count(void *arg) /* Thread T2 routine */ void * count(void *arg) for (i=0; i<10; i++) DOWN(mutex); cnt++; UP(mutex); for (i=0; i<10; i++) DOWN(mutex); cnt++; UP(mutex); Exercise - Understanding Semaphores" What are possible values for g, after the two threads below finish executing?" // global shared variables int g = 10; Semaphore s = 0; Thread A g = g + 1; UP(s); g = g * 2; Thread B DOWN(s); g = g - 2; UP(s); 9

int g = 10; Semaphore s = 0; Thread A R1 = g R1 = R1+1 g = R1 UP(s); R2 = g R2 = R2*2 g = R2 Thread B DOWN(s); R3 = g R3 = R2-2 g = R3 UP(s); Using OS Semaphores" Semaphores have two uses:" - Mutual exclusion: making sure that only one thread is in a critical section at one time" - Synchronization: making sure that T1 completes execution before T2 starts?" 10

Synchronizing Threads with Semaphores" Suppose that we have 2 threads: T1 and T2" How can we ensure that a statement S1 in T1 executes before statement S2 in T2? " Thread T1 Semaphore sync; 0 Thread T2 S1; UP(sync); DOWN(sync); S2; Exercise" " Consider two concurrent threads T1 and T2. T1 executes statements S1 and S3 and T2 executes statement S2." " " "T1 T2 S1 S2 S3 Use semaphores to ensure that S1 always gets executed before S2 and S2 always gets executed before S3" 11

Review: Mutual Exclusion" Semaphore mutex; 1 Thread T1 Thread T2 DOWN(mutex); critical section UP(mutex); DOWN(mutex); critical section UP(mutex); Review: Synchronization" T2 cannot begin execution until T1 has finished:" Semaphore mutex; 0 Thread T1 Code for T1 UP(mutex); Thread T2 DOWN(mutex); Code for T2 12

Deadlock and Starvation" Deadlock occurs when two or more threads are waiting indefinitely for an event that can be caused by only one of the waiting threads " Let S and Q be two semaphores initialized to 1"!!T 1 T 2 " "wait (S); wait (Q); wait (Q); wait (S);...... signal (S); signal (Q); signal (Q); signal (S); Starvation indefinite blocking " - a thread may never be removed from the semaphore queue in which it is suspended" Threads" - Share global data" Problem with Threads " - Races" Summary" Eliminating Races" - Mutual Exclusion with Semaphores" Thread Synchronization" - Use Semaphores" POSIX Threads" 13

Hands-on Session" POSIX semaphores" - sem_init - sem_wait - sem_post - sem_getvalue - sem_destroy Fix the badcnt.c program to produce correct result" - Exercise 2 on class website" 14