So far, we've seen situations in which locking can improve reliability of access to critical sections.

Size: px
Start display at page:

Download "So far, we've seen situations in which locking can improve reliability of access to critical sections."

Transcription

1 Locks Page 1 Using locks Monday, October 6, :49 AM So far, we've seen situations in which locking can improve reliability of access to critical sections. In general, how can one use locks?

2 Locks Page 2 Some important concepts we will emphasize Monday, October 6, :33 PM An atomic operation is something that is not interruptable and occurs in isolation from other operations. A thread-safe operation (or set of operations) has the property that if used by multiple threads, no problems will occur. An async-safe operation (also called reentrant in some circles) is an operation that can safely be invoked in a signal handler.

3 Locks Page 3 A few quandaries to ponder Monday, October 6, :36 PM Pipes and raw I/O are thread-safe. Raw I/O (write) is async-safe but not formatted I/O (printf). Certain operations are atomic, e.g., locking an unlocked mutex. In most cases, being atomic assures both thread-safe and async-safe, but not vice versa.

4 Locks Page 4 The deep semantics of process interaction Tuesday, October 04, :29 PM The deep semantics of process interaction What is a process? What is a thread? What is a pipe? What is a file? What is a file buffer?

5 Locks Page 5 What is a pipe? Monday, October 12, :21 PM Many of the anomalies we can experience are manifest by pipes. To understand these anomalies, it helps to understand what pipes are. The pipe is a very basic building block of operating system processes.

6 Locks Page 6 What is a pipe (cont'd)? Tuesday, October 04, :43 PM What is a pipe? Semantically, a ring buffer of characters (an array queue). write enqueues to the buffer. read dequeues from the buffer. An over-simplification (that we will refine later):

7 Locks Page 7 Looking deeper Monday, October 6, :32 AM What exactly is a pipe? As a first approximation, it is the ring buffer we demonstrated above, with read and write implemented as multiple dequeues/enqueues. But a pipe has to have more properties, including thread-safety and async safety. simultaneous usability by multiple processes. block on read from empty buffer and block on write to full buffer.

8 A simple and profound example Monday, October 6, :34 AM We'll take the simple ring buffer code and make it threadsafe. This is a metaphor for what the OS does to make pipes usable across multiple processes. Step 1: identify critical sections These are the sections that multiple threads should not enter at the same time. // simple example of a ring buffer to explain a pipe #include <stdio.h> #include <string.h> #define PSIZE 8192 char ring[psize]; int begin=0; int end =0; int empty() { return begin==end; int full() { return (end+1)%psize==begin; int used() { return (end-begin+psize)%psize; int avail() { return PSIZE-1-used(); void enqueue(char c) { if (!full()) { ring[end]=c; end=(end+1)%psize; // put one character into the buffer char dequeue() { // remove one character from the buffer char out; if (!empty()) { out=ring[begin]; begin=(begin+1)%psize; return out; else { return '\0'; void read(char *buffer, int size) { // make read atomic while (!used(size)) sleep(1); // parody of blocking while(!empty() && size) { *(buffer++) = dequeue(); size--; Locks Page 8

9 while(!empty() && size) { *(buffer++) = dequeue(); size--; void write(const char *buffer, int size) { // make write atomic while (!avail(size)) sleep(1); // parody of blocking while (!full() && size) { enqueue(*buffer++); size--; char buffer[128]; main() { printf("begin=%d\n",begin); printf("end=%d\n",end); printf("used=%d\n",used()); printf("avail=%d\n",avail()); write("hello",strlen("hello")+1); printf("begin=%d\n",begin); printf("end=%d\n",end); printf("used=%d\n",used()); printf("avail=%d\n",avail()); read(buffer, 6); printf("begin=%d\n",begin); printf("end=%d\n",end); printf("used=%d\n",used()); printf("avail=%d\n",avail()); printf("got %s\n",buffer); From < For an idea of what might go wrong, see Locks Page 9

10 Ring queues in action Tuesday, October 12, :19 PM Locks Page 10

11 Locks Page 11 Locking and schedules Tuesday, October 11, :20 PM Locking and schedules A schedule is a sequence of "what happens when" in a concurrent program. Locks preclude some possible schedules. The game of locking: limit the possible schedules so that only desirable things can happen. WITHOUT LIMITING YOURSELF INTO DEADLOCK.

12 A very bad schedule Monday, October 6, :46 PM A schedule is a matrix of what happened when. Columns are threads. Rows are statements if (!full) update increment if (!full) update full-1 full-1 full-1 increment full-1 full empty Locks Page 12

13 Locks Page 13 The problem Tuesday, October 12, :29 PM It turns out that this code executes perfectly % of the time. But there is a latent problem that is extremely rare. It might happen that an enqueue gets interrupted by another as predicted by the schedule above. Then all havoc breaks loose!

14 Locks Page 14 Designing a threaded P/C program Tuesday, October 12, :39 PM Designing a threaded program: Separate parts of the program into producer and consumer Identify critical sections of shared code that should be atomic. Surround critical sections (that you define) with mutex (mutual exclusion) locks.

15 Locks Page 15 Sharing the ring buffer Tuesday, October 12, :27 PM void *threaded_routine_1 (void * v) { int i; printf ("hello from the thread!\n"); for(i=0; i<200; i++) { while(full()) ; enqueue('a'+(i%26)); sleep(1); enqueue(0); printf ("bye from the thread!\n"); return NULL; void *threaded_routine_2 (void * v) { int i; printf ("hello from the thread!\n"); for(i=0; i<200; i++) { while(full()) ; enqueue('0'+(i%10)); sleep(1); enqueue(0); printf ("bye from the thread!\n"); return NULL; main() { pthread_t thread; void *retptr; printf("hello from the parent... creating thread\n"); pthread_create( &thread, NULL, threaded_routine_1, NULL); pthread_create( &thread, NULL, threaded_routine_2, NULL); while (1) { while(empty()) ; char c = dequeue(); printf("parent got %c\n",c); if (c==0) break; pthread_join(thread,(void **)&retptr);

16 Locks Page 16 pthread_join(thread,(void **)&retptr); printf("bye from the parent\n"); Pasted from <

17 Locks Page 17 Steps in solving the problem Tuesday, October 12, :30 PM Steps in solving the problem Identify critical sections that should be atomic. Surround these with mutex locks.

18 Locks Page 18 What are the critical sections? Tuesday, October 12, :30 PM #define SIZE 50 int begin=0, end=0; char queue[size]; int empty() { return begin==end; int full() { return ((end+1)%size)==begin; void enqueue(char c) { // BEGIN CRITICAL SECTION if (!full()) { queue[end]=c; end=(end+1)%size; else { fprintf(stderr,"queue full\n"); // END CRITICAL SECTION char dequeue() { // BEGIN CRITICAL SECTION if (!empty()) { char out = queue[begin]; begin=(begin+1)%size; // END CRITICAL SECTION return out; else { // END CRITICAL SECTION fprintf(stderr,"queue empty\n"); return 0; Pasted from <

19 Locks Page 19 Problem solved Tuesday, October 12, :33 PM #define SIZE 50 int begin=0, end=0; char queue[size]; int empty() { return begin==end; int full() { return ((end+1)%size)==begin; void enqueue(char c) { pthread_mutex_lock(&locker); if (!full()) { queue[end]=c; end=(end+1)%size; else { fprintf(stderr,"queue full\n"); pthread_mutex_unlock(&locker); char dequeue() { pthread_mutex_lock(&locker); if (!empty()) { char out = queue[begin]; begin=(begin+1)%size; pthread_mutex_unlock(&locker); return out; else { pthread_mutex_unlock(&locker); fprintf(stderr,"queue empty\n"); return 0; Pasted from <

20 Locks Page 20 The important fact... Wednesday, October 8, :13 PM Is not so much that the process stops until it can achieve a lock. It is that the process is blocked and not runnable (outside the run queue) until it gets the lock. => you can use locks to block programs, independent of their critical sections.

21 A better approach Thursday, October 14, :08 PM Locks are not just to protect critical sections! In fact, one can utilize mutexes to block I/O! pthread_mutex_t notempty; pthread_mutex_t notfull; #define SIZE 50 int begin=0, end=0; char queue[size]; // in essence, make these private inline int empty() { return begin==end; inline int full() { return ((end+1)%size)==begin; void enqueue(char c) { int e; pthread_mutex_lock(&notfull); // wait until not full! pthread_mutex_lock(&modify); // modify queue /// BEGIN CRITICAL SECTION e=empty(); queue[end]=c; end=(end+1)%size; if (e) pthread_mutex_unlock(&notempty); // ok for dequeue to run now. if (!full()) pthread_mutex_unlock(&notfull); // ok to do another enqueue /// END CRITICAL SECTION pthread_mutex_unlock(&modify); char dequeue() { int f; char out; pthread_mutex_lock(&notempty); // wait until not empty pthread_mutex_lock(&modify); // modify queue /// BEGIN CRITICAL SECTION f = full(); out = queue[begin]; begin=(begin+1)%size; if (f) pthread_mutex_unlock(&notfull); // ok for enqueue to work if (!empty()) pthread_mutex_unlock(&notempty); // ok for another dequeue /// END CRITICAL SECTION pthread_mutex_unlock(&modify); return out; Locks Page 21

22 See Locks Page 22

23 Locks Page 23 Some notes on this solution Wednesday, October 11, :11 PM When you lock notfull, you know that the state is not full and that no one else can do anything with that state but you. When you unlock notfull, you allow someone else to lock it. When you lock notempty, you know that the state is not empty you are the only one who can act on that state.

24 Locks Page 24 A bit of tuning Monday, October 12, :45 PM The critical sections in the preceeding are too long. Instead of pthread_mutex_lock(modify); // modify queue /// BEGIN CRITICAL SECTION f = full(); out = queue[begin]; begin=(begin+1)%size; if (f) pthread_mutex_unlock(&notfull); // ok for enqueue to work if (!empty()) pthread_mutex_unlock(&notempty); // ok for another dequeue /// END CRITICAL SECTION pthread_mutex_unlock(&modify); we can write: pthread_mutex_lock(modify); // modify queue /// BEGIN CRITICAL SECTION f = full(); out = queue[begin]; begin=(begin+1)%size; e = empty(); /// END CRITICAL SECTION pthread_mutex_unlock(&modify); if (f) pthread_mutex_unlock(&notfull); // ok for enqueue to work if (!e) pthread_mutex_unlock(&notempty); // ok for another dequeue See ck5.c

25 Locks Page 25 The bounded buffer queue Wednesday, October 8, :02 AM The previous example/pattern is called the bounded buffer queue. Dequeueing thread blocks on dequeue from empty queue until input present. Enqueueing thread blocks on enqueue of full queue until dequeue creates room. This is a basic building block for all producer/consumer programs.

26 Locks Page 26 Why this works Thursday, October 14, :14 PM Why this works: notfull is unlocked => can enqueue notfull is locked => can' t enqueue because queue is full notempty is unlocked => can dequeue notempty is locked => can't dequeue because queue is empty

27 Locks Page 27 Locks and proof Thursday, October 14, :16 PM There is no debugging method that can determine whether the preceding code is "correct". We need: No deadlocks. No critical section conflicts. Instead, one must "prove" correctness by careful reasoning. Express the states of the system Show how state transitions occur and why.

28 Locks Page 28 A "proof" that notfull and notempty work Thursday, October 14, :17 PM There are three states of the queue empty: nothing there, dequeue impossible. full: filled up, enqueue impossible. part-full (or part-empty): entries present, enqueue and dequeue possible. But also note that: enqueue only modifies the "end" index. dequeue only modifies the "begin" index. only one of enqueue or dequeue can enter the critical section at a time.

29 A picture of locking state Thursday, October 14, :22 PM Enqueue running Neither enqueue nor dequeue running Both enqueue and dequeue running simultaneously Dequeue running Locks Page 29

30 Locks Page 30 End of lecture on 10/11/2017 Wednesday, October 11, :55 PM

31 Locks Page 31 A true horror story Tuesday, October 11, :26 PM A true horror story When I was working on this example, I had an extremely subtle locking error. I started by testing the example without the modify lock: void enqueue(char c) { int e; pthread_mutex_lock(&notfull); // wait until not full! pthread_mutex_lock(&modify); // modify queue /// BEGIN CRITICAL SECTION e=empty(); queue[end]=c; end=(end+1)%size; if (e) pthread_mutex_unlock(&notempty); if (!full()) pthread_mutex_unlock(&notfull); /// END CRITICAL SECTION pthread_mutex_unlock(&modify); char dequeue() { int f; char out; pthread_mutex_lock(&notempty); // wait until not empty pthread_mutex_lock(modify); // modify queue /// BEGIN CRITICAL SECTION f = full(); out = queue[begin]; begin=(begin+1)%size; if (f) pthread_mutex_unlock(&notfull); if (!empty()) pthread_mutex_unlock(&notempty); /// END CRITICAL SECTION pthread_mutex_unlock(&modify); return out; This worked, but failed about 1/100 of the time. So I started checking for issues, and found that: It's ok for enqueue and dequeue to happen at the same time as far as the data structure goes, but It's not ok as far as modifying the lock states!

32 Locks Page 32 The problem is that the statements that test empty() and full() to accomplish state transitions may skip an unlock of a critical lock. One scenerio: queue nearly empty. Call dequeue and enqueue at the same time. Dequeue empties the queue. Enqueue adds an element. Then!empty() is checked. Result: notempty is not unlocked!

Threads Tuesday, September 28, :37 AM

Threads Tuesday, September 28, :37 AM Threads_and_fabrics Page 1 Threads Tuesday, September 28, 2004 10:37 AM Threads A process includes an execution context containing Memory map PC and register values. Switching between memory maps can take

More information

So far, we know: Wednesday, October 4, Thread_Programming Page 1

So far, we know: Wednesday, October 4, Thread_Programming Page 1 Thread_Programming Page 1 So far, we know: 11:50 AM How to create a thread via pthread_mutex_create How to end a thread via pthread_mutex_join How to lock inside a thread via pthread_mutex_lock and pthread_mutex_unlock.

More information

Solving the Producer Consumer Problem with PThreads

Solving the Producer Consumer Problem with PThreads Solving the Producer Consumer Problem with PThreads Michael Jantz Dr. Prasad Kulkarni Dr. Douglas Niehaus EECS 678 Pthreads: Producer-Consumer 1 Introduction This lab is an extension of last week's lab.

More information

More Shared Memory Programming

More Shared Memory Programming More Shared Memory Programming Shared data structures We want to make data structures that can be shared by threads. For example, our program to copy a file from one disk to another used a shared FIFO

More information

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

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Operating Systems Lecture 4 - Concurrency and Synchronization Adrien Krähenbühl Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Mutual exclusion Hardware solutions Semaphores IPC: Message passing

More information

Recall from deadlock lecture. Tuesday, October 18, 2011

Recall from deadlock lecture. Tuesday, October 18, 2011 Recall from deadlock lecture Tuesday, October 18, 2011 1:17 PM Basic assumptions of deadlock theory: If a process gets the resources it requests, it completes, exits, and releases resources. There are

More information

Midterm on next week Tuesday May 4. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9

Midterm on next week Tuesday May 4. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9 CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

More information

Synchronising Threads

Synchronising Threads Synchronising Threads David Chisnall March 1, 2011 First Rule for Maintainable Concurrent Code No data may be both mutable and aliased Harder Problems Data is shared and mutable Access to it must be protected

More information

Epilogue. Thursday, December 09, 2004

Epilogue. Thursday, December 09, 2004 Epilogue Thursday, December 09, 2004 2:16 PM We have taken a rather long journey From the physical hardware, To the code that manages it, To the optimal structure of that code, To models that describe

More information

CS 450 Exam 2 Mon. 4/11/2016

CS 450 Exam 2 Mon. 4/11/2016 CS 450 Exam 2 Mon. 4/11/2016 Name: Rules and Hints You may use one handwritten 8.5 11 cheat sheet (front and back). This is the only additional resource you may consult during this exam. No calculators.

More information

CMSC421: Principles of Operating Systems

CMSC421: Principles of Operating Systems CMSC421: Principles of Operating Systems Nilanjan Banerjee Assistant Professor, University of Maryland Baltimore County nilanb@umbc.edu http://www.csee.umbc.edu/~nilanb/teaching/421/ Principles of Operating

More information

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018 Deadlock and Monitors CS439: Principles of Computer Systems September 24, 2018 Bringing It All Together Processes Abstraction for protection Define address space Threads Share (and communicate) through

More information

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

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 Process creation in UNIX All processes have a unique process id getpid(),

More information

CS4961 Parallel Programming. Lecture 12: Advanced Synchronization (Pthreads) 10/4/11. Administrative. Mary Hall October 4, 2011

CS4961 Parallel Programming. Lecture 12: Advanced Synchronization (Pthreads) 10/4/11. Administrative. Mary Hall October 4, 2011 CS4961 Parallel Programming Lecture 12: Advanced Synchronization (Pthreads) Mary Hall October 4, 2011 Administrative Thursday s class Meet in WEB L130 to go over programming assignment Midterm on Thursday

More information

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

So far, system calls have had easy syntax. Integer, character string, and structure arguments. Pointers Page 1 So far, system calls have had easy syntax Wednesday, September 30, 2015 10:45 AM Integer, character string, and structure arguments. But this is not always true. Today, we begin to explore

More information

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

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017 CS 471 Operating Systems Yue Cheng George Mason University Fall 2017 1 Review: Sync Terminology Worksheet 2 Review: Semaphores 3 Semaphores o Motivation: Avoid busy waiting by blocking a process execution

More information

Implementing Mutual Exclusion. Sarah Diesburg Operating Systems CS 3430

Implementing Mutual Exclusion. Sarah Diesburg Operating Systems CS 3430 Implementing Mutual Exclusion Sarah Diesburg Operating Systems CS 3430 From the Previous Lecture The too much milk example shows that writing concurrent programs directly with load and store instructions

More information

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions Announcements Thursday Extras: CS Commons on Thursdays @ 4:00 pm but none next week No office hours next week Monday or Tuesday Reflections: when to use if/switch statements for/while statements Floating-point

More information

Synchronization Primitives

Synchronization Primitives Synchronization Primitives Locks Synchronization Mechanisms Very primitive constructs with minimal semantics Semaphores A generalization of locks Easy to understand, hard to program with Condition Variables

More information

CS 3305 Intro to Threads. Lecture 6

CS 3305 Intro to Threads. Lecture 6 CS 3305 Intro to Threads Lecture 6 Introduction Multiple applications run concurrently! This means that there are multiple processes running on a computer Introduction Applications often need to perform

More information

Deadlock and Monitors. CS439: Principles of Computer Systems February 7, 2018

Deadlock and Monitors. CS439: Principles of Computer Systems February 7, 2018 Deadlock and Monitors CS439: Principles of Computer Systems February 7, 2018 Last Time Terminology Safety and liveness Atomic Instructions, Synchronization, Mutual Exclusion, Critical Sections Synchronization

More information

CSE 120. Fall Lecture 6: Semaphores. Keith Marzullo

CSE 120. Fall Lecture 6: Semaphores. Keith Marzullo CSE 120 Principles of Operating Systems Fall 2007 Lecture 6: Semaphores Keith Marzullo Announcements Homework #2 out Homework #1 almost graded... Discussion session on Wednesday will entertain questions

More information

Page 1. Goals for Today" Atomic Read-Modify-Write instructions" Examples of Read-Modify-Write "

Page 1. Goals for Today Atomic Read-Modify-Write instructions Examples of Read-Modify-Write Goals for Today" CS162 Operating Systems and Systems Programming Lecture 5 Semaphores, Conditional Variables" Atomic instruction sequence Continue with Synchronization Abstractions Semaphores, Monitors

More information

Last Class: Deadlocks. Today

Last Class: Deadlocks. Today Last Class: Deadlocks Necessary conditions for deadlock: Mutual exclusion Hold and wait No preemption Circular wait Ways of handling deadlock Deadlock detection and recovery Deadlock prevention Deadlock

More information

What's wrong with Semaphores?

What's wrong with Semaphores? Next: Monitors and Condition Variables What is wrong with semaphores? Monitors What are they? How do we implement monitors? Two types of monitors: Mesa and Hoare Compare semaphore and monitors Lecture

More information

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

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 The Process Concept 2 The Process Concept Process a program in execution

More information

Introduction to Embedded Systems

Introduction to Embedded Systems Introduction to Embedded Systems Edward A. Lee & Sanjit Seshia UC Berkeley EECS 124 Spring 2008 Copyright 2008, Edward A. Lee & Sanjit Seshia, All rights reserved Lecture 17: Concurrency 2: Threads Definition

More information

CSE373 Fall 2013, Second Midterm Examination November 15, 2013

CSE373 Fall 2013, Second Midterm Examination November 15, 2013 CSE373 Fall 2013, Second Midterm Examination November 15, 2013 Please do not turn the page until the bell rings. Rules: The exam is closed-book, closed-note, closed calculator, closed electronics. Please

More information

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Synchronization Exercise

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Synchronization Exercise CSE120 Principles of Operating Systems Prof Yuanyuan (YY) Zhou Synchronization Exercise A good review video l https://www.youtube.com/watch?v=1bvyjmgiaeu l Correction: CPU doesn t do scheduling. It is

More information

CMSC421: Principles of Operating Systems

CMSC421: Principles of Operating Systems CMSC421: Principles of Operating Systems Nilanjan Banerjee Assistant Professor, University of Maryland Baltimore County nilanb@umbc.edu http://www.csee.umbc.edu/~nilanb/teaching/421/ Principles of Operating

More information

0x0d2C May your signals all trap May your references be bounded All memory aligned Floats to ints round. remember...

0x0d2C May your signals all trap May your references be bounded All memory aligned Floats to ints round. remember... Types Page 1 "ode to C" Monday, September 18, 2006 4:09 PM 0x0d2C ------ May your signals all trap May your references be bounded All memory aligned Floats to ints round remember... Non -zero is true ++

More information

Operating systems. Lecture 12

Operating systems. Lecture 12 Operating systems. Lecture 12 Michał Goliński 2018-12-18 Introduction Recall Critical section problem Peterson s algorithm Synchronization primitives Mutexes Semaphores Plan for today Classical problems

More information

COMP 3430 Robert Guderian

COMP 3430 Robert Guderian Operating Systems COMP 3430 Robert Guderian file:///users/robg/dropbox/teaching/3430-2018/slides/06_concurrency/index.html?print-pdf#/ 1/76 1 Concurrency file:///users/robg/dropbox/teaching/3430-2018/slides/06_concurrency/index.html?print-pdf#/

More information

Race Conditions & Synchronization

Race Conditions & Synchronization Race Conditions & Synchronization Lecture 25 Spring 2017 Gries office hours 2 A number of students have asked for time to talk over how to study for the prelim. Gries will hold office hours at the times

More information

CSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks

CSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks CSci 4061 Introduction to Operating Systems Synchronization Basics: Locks Synchronization Outline Basics Locks Condition Variables Semaphores Basics Race condition: threads + shared data Outcome (data

More information

Synchronization 1. Synchronization

Synchronization 1. Synchronization Synchronization 1 Synchronization key concepts critical sections, mutual exclusion, test-and-set, spinlocks, blocking and blocking locks, semaphores, condition variables, deadlocks reading Three Easy Pieces:

More information

Page 1. Goals for Today" Atomic Read-Modify-Write instructions" Examples of Read-Modify-Write "

Page 1. Goals for Today Atomic Read-Modify-Write instructions Examples of Read-Modify-Write Goals for Today" CS162 Operating Systems and Systems Programming Lecture 5 Semaphores, Conditional Variables" Atomic instruction sequence Continue with Synchronization Abstractions Semaphores, Monitors

More information

Lecture 5 Threads and Pthreads II

Lecture 5 Threads and Pthreads II CSCI-GA.3033-017 Special Topics: Multicore Programming Lecture 5 Threads and Pthreads II Christopher Mitchell, Ph.D. cmitchell@cs.nyu.edu http://z80.me Context We re exploring the layers of an application

More information

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07 Informatica 3 Marcello Restelli 9/15/07 10/29/07 Laurea in Ingegneria Informatica Politecnico di Milano Structuring the Computation Control flow can be obtained through control structure at instruction

More information

Condition Variables & Semaphores

Condition Variables & Semaphores Condition Variables & Semaphores Nima Honarmand (Based on slides by Prof. Andrea Arpaci-Dusseau) Review: Concurrency Objectives Mutual Exclusion A & B don t run at the same time Solved using locks Ordering

More information

Announcements. CS 3204 Operating Systems. Schedule. Optimistic Concurrency Control. Optimistic Concurrency Control (2)

Announcements. CS 3204 Operating Systems. Schedule. Optimistic Concurrency Control. Optimistic Concurrency Control (2) Announcements CS 3204 Operating Systems Lecture 15 Godmar Back Project 2 due Tuesday Oct 17, 11:59pm Midterm Thursday Oct 12 Posted Midterm Announcement Posted Sample Midterm Reading assignment: Read Chapter

More information

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor.

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor. Synchronization 1 Concurrency On multiprocessors, several threads can execute simultaneously, one on each processor. On uniprocessors, only one thread executes at a time. However, because of preemption

More information

Programming in Parallel COMP755

Programming in Parallel COMP755 Programming in Parallel COMP755 All games have morals; and the game of Snakes and Ladders captures, as no other activity can hope to do, the eternal truth that for every ladder you hope to climb, a snake

More information

CS 6400 Lecture 11 Name:

CS 6400 Lecture 11 Name: Readers and Writers Example - Granularity Issues. Multiple concurrent readers, but exclusive access for writers. Original Textbook code with ERRORS - What are they? Lecture 11 Page 1 Corrected Textbook

More information

Thread. Disclaimer: some slides are adopted from the book authors slides with permission 1

Thread. Disclaimer: some slides are adopted from the book authors slides with permission 1 Thread Disclaimer: some slides are adopted from the book authors slides with permission 1 IPC Shared memory Recap share a memory region between processes read or write to the shared memory region fast

More information

Page 1. Goals for Today. Atomic Read-Modify-Write instructions. Examples of Read-Modify-Write

Page 1. Goals for Today. Atomic Read-Modify-Write instructions. Examples of Read-Modify-Write Goals for Today CS162 Operating Systems and Systems Programming Lecture 5 Atomic instruction sequence Continue with Synchronization Abstractions Semaphores, Monitors and condition variables Semaphores,

More information

Lecture 21: Transactional Memory. Topics: consistency model recap, introduction to transactional memory

Lecture 21: Transactional Memory. Topics: consistency model recap, introduction to transactional memory Lecture 21: Transactional Memory Topics: consistency model recap, introduction to transactional memory 1 Example Programs Initially, A = B = 0 P1 P2 A = 1 B = 1 if (B == 0) if (A == 0) critical section

More information

High Performance Computing Course Notes Shared Memory Parallel Programming

High Performance Computing Course Notes Shared Memory Parallel Programming High Performance Computing Course Notes 2009-2010 2010 Shared Memory Parallel Programming Techniques Multiprocessing User space multithreading Operating system-supported (or kernel) multithreading Distributed

More information

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico. Java Monitors Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico October 19, 2010 Monteiro, Costa (DEI / IST) Parallel and Distributed Computing

More information

CSE 120 Principles of Operating Systems Spring 2016

CSE 120 Principles of Operating Systems Spring 2016 CSE 120 Principles of Operating Systems Spring 2016 Condition Variables and Monitors Monitors A monitor is a programming language construct that controls access to shared data Synchronization code added

More information

Lecture 6 (cont.): Semaphores and Monitors

Lecture 6 (cont.): Semaphores and Monitors Project 1 Due Thursday 10/20 Lecture 6 (cont.): Semaphores and Monitors CSE 120: Principles of Operating Systems Alex C. Snoeren Higher-Level Synchronization We looked at using locks to provide mutual

More information

Synchronization. CS61, Lecture 18. Prof. Stephen Chong November 3, 2011

Synchronization. CS61, Lecture 18. Prof. Stephen Chong November 3, 2011 Synchronization CS61, Lecture 18 Prof. Stephen Chong November 3, 2011 Announcements Assignment 5 Tell us your group by Sunday Nov 6 Due Thursday Nov 17 Talks of interest in next two days Towards Predictable,

More information

Computer Science 61 Scribe Notes Tuesday, November 25, 2014 (aka the day before Thanksgiving Break)

Computer Science 61 Scribe Notes Tuesday, November 25, 2014 (aka the day before Thanksgiving Break) Computer Science 61 Scribe Notes Tuesday, November 25, 2014 (aka the day before Thanksgiving Break) Problem Set 6 Released! People have fun with it Make Games Snake Game Hack JavaScript Due Wed., last

More information

Inside core.async Channels. Rich Hickey

Inside core.async Channels. Rich Hickey Inside core.async s Rich Hickey Warning! Implementation details Subject to change The Problems Single channel implementation For use from both dedicated threads and go threads simultaneously, on same channel

More information

Last Class: Synchronization

Last Class: Synchronization Last Class: Synchronization Synchronization primitives are required to ensure that only one thread executes in a critical section at a time. Concurrent programs Low-level atomic operations (hardware) load/store

More information

Intertask Communication

Intertask Communication Inter-task Communication 04/27/01 Lecture # 29 16.070 Task state diagram (single processor) Intertask Communication Global variables Buffering data Critical regions Synchronization Semaphores Mailboxes

More information

Synchronization. Announcements. Concurrent Programs. Race Conditions. Race Conditions 11/9/17. Purpose of this lecture. A8 released today, Due: 11/21

Synchronization. Announcements. Concurrent Programs. Race Conditions. Race Conditions 11/9/17. Purpose of this lecture. A8 released today, Due: 11/21 Announcements Synchronization A8 released today, Due: 11/21 Late deadline is after Thanksgiving You can use your A6/A7 solutions or ours A7 correctness scores have been posted Next week's recitation will

More information

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology exam Embedded Software TI2726-B January 28, 2019 13.30-15.00 This exam (6 pages) consists of 60 True/False

More information

CS533 Concepts of Operating Systems. Jonathan Walpole

CS533 Concepts of Operating Systems. Jonathan Walpole CS533 Concepts of Operating Systems Jonathan Walpole Introduction to Threads and Concurrency Why is Concurrency Important? Why study threads and concurrent programming in an OS class? What is a thread?

More information

Multithreading Programming II

Multithreading Programming II Multithreading Programming II Content Review Multithreading programming Race conditions Semaphores Thread safety Deadlock Review: Resource Sharing Access to shared resources need to be controlled to ensure

More information

Systems Programming/ C and UNIX

Systems Programming/ C and UNIX Systems Programming/ C and UNIX Alice E. Fischer November 22, 2013 Alice E. Fischer () Systems Programming Lecture 12... 1/27 November 22, 2013 1 / 27 Outline 1 Jobs and Job Control 2 Shared Memory Concepts

More information

Operating Systems CMPSC 473. Synchronization February 26, Lecture 12 Instructor: Trent Jaeger

Operating Systems CMPSC 473. Synchronization February 26, Lecture 12 Instructor: Trent Jaeger Operating Systems CMPSC 473 Synchronization February 26, 2008 - Lecture 12 Instructor: Trent Jaeger Last class: Synchronization Problems and Primitives Today: Synchonization Solutions Midterm (Both Sections)

More information

Condition Variables CS 241. Prof. Brighten Godfrey. March 16, University of Illinois

Condition Variables CS 241. Prof. Brighten Godfrey. March 16, University of Illinois Condition Variables CS 241 Prof. Brighten Godfrey March 16, 2012 University of Illinois 1 Synchronization primitives Mutex locks Used for exclusive access to a shared resource (critical section) Operations:

More information

CSE 486/586 Distributed Systems

CSE 486/586 Distributed Systems CSE 486/586 Distributed Systems Mutual Exclusion Steve Ko Computer Sciences and Engineering University at Buffalo CSE 486/586 Recap: Consensus On a synchronous system There s an algorithm that works. On

More information

Reminder from last time

Reminder from last time Concurrent systems Lecture 2: More mutual exclusion, semaphores, and producer-consumer relationships DrRobert N. M. Watson 1 Reminder from last time Definition of a concurrent system Origins of concurrency

More information

Database Management System Prof. D. Janakiram Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Database Management System Prof. D. Janakiram Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No. Database Management System Prof. D. Janakiram Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No. # 20 Concurrency Control Part -1 Foundations for concurrency

More information

CS 25200: Systems Programming. Lecture 26: Classic Synchronization Problems

CS 25200: Systems Programming. Lecture 26: Classic Synchronization Problems CS 25200: Systems Programming Lecture 26: Classic Synchronization Problems Dr. Jef Turkstra 2018 Dr. Jeffrey A. Turkstra 1 Announcements Lab 5 posted this evening Web server Password protection SSL cgi-bin

More information

CSE 153 Design of Operating Systems

CSE 153 Design of Operating Systems CSE 153 Design of Operating Systems Winter 19 Lecture 7/8: Synchronization (1) Administrivia How is Lab going? Be prepared with questions for this weeks Lab My impression from TAs is that you are on track

More information

Today: Synchronization. Recap: Synchronization

Today: Synchronization. Recap: Synchronization Today: Synchronization Synchronization Mutual exclusion Critical sections Example: Too Much Milk Locks Synchronization primitives are required to ensure that only one thread executes in a critical section

More information

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor.

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor. Synchronization 1 Concurrency On multiprocessors, several threads can execute simultaneously, one on each processor. On uniprocessors, only one thread executes at a time. However, because of preemption

More information

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst Operating Systems CMPSCI 377 Spring 2017 Mark Corner University of Massachusetts Amherst What is a Monitor? Ties data and the synchronization operations together Monitors guarantee mutual exclusion, i.e.,

More information

CSEN 602-Operating Systems, Spring 2018 Practice Assignment 2 Solutions Discussion:

CSEN 602-Operating Systems, Spring 2018 Practice Assignment 2 Solutions Discussion: CSEN 602-Operating Systems, Spring 2018 Practice Assignment 2 Solutions Discussion: 10.2.2018-15.2.2018 Exercise 2-1: Reading Read sections 2.1 (except 2.1.7), 2.2.1 till 2.2.5. 1 Exercise 2-2 In Fig.1,

More information

Introduction to Operating Systems Prof. Chester Rebeiro Department of Computer Science and Engineering Indian Institute of Technology, Madras

Introduction to Operating Systems Prof. Chester Rebeiro Department of Computer Science and Engineering Indian Institute of Technology, Madras Introduction to Operating Systems Prof. Chester Rebeiro Department of Computer Science and Engineering Indian Institute of Technology, Madras Week 06 Lecture 29 Semaphores Hello. In this video, we will

More information

Virtual Machine Design

Virtual Machine Design Virtual Machine Design Lecture 4: Multithreading and Synchronization Antero Taivalsaari September 2003 Session #2026: J2MEPlatform, Connected Limited Device Configuration (CLDC) Lecture Goals Give an overview

More information

CS 318 Principles of Operating Systems

CS 318 Principles of Operating Systems CS 318 Principles of Operating Systems Fall 2017 Midterm Review Ryan Huang 10/12/17 CS 318 Midterm Review 2 Midterm October 17 th Tuesday 9:00-10:20 am at classroom Covers material before virtual memory

More information

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010 CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion Tyler Robison Summer 2010 1 Toward sharing resources (memory) So far we ve looked at parallel algorithms using fork-join

More information

Lecture 7: Transactional Memory Intro. Topics: introduction to transactional memory, lazy implementation

Lecture 7: Transactional Memory Intro. Topics: introduction to transactional memory, lazy implementation Lecture 7: Transactional Memory Intro Topics: introduction to transactional memory, lazy implementation 1 Transactions New paradigm to simplify programming instead of lock-unlock, use transaction begin-end

More information

Announcements. CS18000: Problem Solving And Object-Oriented Programming

Announcements. CS18000: Problem Solving And Object-Oriented Programming Announcements Exam 1 Monday, February 28 Wetherill 200, 4:30pm-5:20pm Coverage: Through Week 6 Project 2 is a good study mechanism Final Exam Tuesday, May 3, 3:20pm-5:20pm, PHYS 112 If you have three or

More information

Last Class: CPU Scheduling! Adjusting Priorities in MLFQ!

Last Class: CPU Scheduling! Adjusting Priorities in MLFQ! Last Class: CPU Scheduling! Scheduling Algorithms: FCFS Round Robin SJF Multilevel Feedback Queues Lottery Scheduling Review questions: How does each work? Advantages? Disadvantages? Lecture 7, page 1

More information

What does IRET do, anyway?... Exam #1 Feb. 27, 2004

What does IRET do, anyway?... Exam #1 Feb. 27, 2004 15-410...What does IRET do, anyway?... Exam #1 Feb. 27, 2004 Dave Eckhardt Bruce Maggs - 1 - L18_Exam1 Synchronization Final Exam list posted You must notify us of conflicts in a timely fashion P3 milestones

More information

CSE 120 Principles of Operating Systems Spring 2016

CSE 120 Principles of Operating Systems Spring 2016 CSE 120 Principles of Operating Systems Spring 2016 Using Semaphores and Condition Variables Higher-Level Synchronization We looked at using locks to provide mutual exclusion Locks work, but they have

More information

This exam paper contains 8 questions (12 pages) Total 100 points. Please put your official name and NOT your assumed name. First Name: Last Name:

This exam paper contains 8 questions (12 pages) Total 100 points. Please put your official name and NOT your assumed name. First Name: Last Name: CSci 4061: Introduction to Operating Systems (Spring 2013) Final Exam May 14, 2013 (4:00 6:00 pm) Open Book and Lecture Notes (Bring Your U Photo Id to the Exam) This exam paper contains 8 questions (12

More information

Condition Variables. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Condition Variables. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University Condition Variables Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu)

More information

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

CS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization CS-345 Operating Systems Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization Threads A thread is a lightweight process A thread exists within a process and uses the process resources. It

More information

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004 Lecture 8: Semaphores, Monitors, & Condition Variables 8.0 Main Points: Definition of semaphores Example of use

More information

COSC 2P95 Lab 9 Signals, Mutexes, and Threads

COSC 2P95 Lab 9 Signals, Mutexes, and Threads COSC 2P95 Lab 9 Signals, Mutexes, and Threads Sometimes, we can't achieve what we want via a single execution pipeline. Whether it's for responsiveness, or to process more data simultaneously, we rely

More information

Pre- and post- CS protocols. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 7. Other requirements for a mutual exclusion algorithm

Pre- and post- CS protocols. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 7. Other requirements for a mutual exclusion algorithm CS 361 Concurrent programming Drexel University Fall 2004 Lecture 7 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

More information

COSC 6374 Parallel Computation. Shared memory programming with POSIX Threads. Edgar Gabriel. Fall References

COSC 6374 Parallel Computation. Shared memory programming with POSIX Threads. Edgar Gabriel. Fall References COSC 6374 Parallel Computation Shared memory programming with POSIX Threads Fall 2012 References Some of the slides in this lecture is based on the following references: http://www.cobweb.ecn.purdue.edu/~eigenman/ece563/h

More information

[537] Locks and Condition Variables. Tyler Harter

[537] Locks and Condition Variables. Tyler Harter [537] Locks and Condition Variables Tyler Harter Review: using and designing basic locks Do it. Problem 1 Lock Evaluation How to tell if a lock implementation is good? Lock Evaluation How to tell if a

More information

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

CS 333 Introduction to Operating Systems Class 4 Concurrent Programming and Synchronization Primitives CS 333 Introduction to Operating Systems Class 4 Concurrent Programming and Synchronization Primitives Jonathan Walpole Computer Science Portland State University 1 What does a typical thread API look

More information

Operating Systems ECE344

Operating Systems ECE344 Operating Systems ECE344 Ding Yuan Announcement & Reminder Lab 0 mark posted on Piazza Great job! One problem: compilation error I fixed some for you this time, but won t do it next time Make sure you

More information

Synchronization 1. Synchronization

Synchronization 1. Synchronization Synchronization 1 Synchronization key concepts critical sections, mutual exclusion, test-and-set, spinlocks, blocking and blocking locks, semaphores, condition variables, deadlocks reading Three Easy Pieces:

More information

Recap: Thread. What is it? What does it need (thread private)? What for? How to implement? Independent flow of control. Stack

Recap: Thread. What is it? What does it need (thread private)? What for? How to implement? Independent flow of control. Stack What is it? Recap: Thread Independent flow of control What does it need (thread private)? Stack What for? Lightweight programming construct for concurrent activities How to implement? Kernel thread vs.

More information

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems Synchronization CS 475, Spring 2018 Concurrent & Distributed Systems Review: Threads: Memory View code heap data files code heap data files stack stack stack stack m1 m1 a1 b1 m2 m2 a2 b2 m3 m3 a3 m4 m4

More information

ANSI/IEEE POSIX Standard Thread management

ANSI/IEEE POSIX Standard Thread management Pthread Prof. Jinkyu Jeong( jinkyu@skku.edu) TA Jinhong Kim( jinhong.kim@csl.skku.edu) TA Seokha Shin(seokha.shin@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu The

More information

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University Semaphores Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu) Synchronization

More information

Software Engineering CSE 335, Spring OO design: Concurrency and Distribution

Software Engineering CSE 335, Spring OO design: Concurrency and Distribution Software Engineering CSE 335, Spring 2006 OO design: Concurrency and Distribution Stephen Wagner Michigan State University Definitions Process: Program in execution Created and managed by the operating

More information

Locks and semaphores. Johan Montelius KTH

Locks and semaphores. Johan Montelius KTH Locks and semaphores Johan Montelius KTH 2017 1 / 41 recap, what s the problem : # include < pthread.h> volatile int count = 0; void * hello ( void * arg ) { for ( int i = 0; i < 10; i ++) { count ++;

More information

Lecture 6. Process Synchronization

Lecture 6. Process Synchronization Lecture 6 Process Synchronization 1 Lecture Contents 1. Principles of Concurrency 2. Hardware Support 3. Semaphores 4. Monitors 5. Readers/Writers Problem 2 1. Principles of Concurrency OS design issue

More information

Threads need to synchronize their activities to effectively interact. This includes:

Threads need to synchronize their activities to effectively interact. This includes: KING FAHD UNIVERSITY OF PETROLEUM AND MINERALS Information and Computer Science Department ICS 431 Operating Systems Lab # 8 Threads Synchronization ( Mutex & Condition Variables ) Objective: When multiple

More information