[537] Locks and Condition Variables. Tyler Harter

Size: px
Start display at page:

Download "[537] Locks and Condition Variables. Tyler Harter"

Transcription

1 [537] Locks and Condition Variables Tyler Harter

2 Review: using and designing basic locks

3 Do it. Problem 1

4 Lock Evaluation How to tell if a lock implementation is good?

5 Lock Evaluation How to tell if a lock implementation is good? Fairness: does everybody get a chance to use the lock? Performance - high contention (many threads per CPU, each contending) - low contention (fewer threads, fewer locking attempts)

6 Lock Evaluation How to tell if a lock implementation is good? Fairness: does everybody get a chance to use the lock? Performance - high contention (many threads per CPU, each contending) - low contention (fewer threads, fewer locking attempts) which are spinlocks better for?

7 Ticket Lock Review turn = 6 ticket = 6

8 turn = 6 ticket = 6

9 A lock(): gets ticket 6, runs 6 A turn = 6 ticket = 7

10 A lock(): gets ticket 6, runs B lock(): gets ticket 7, spins until turn=7 6 7 A B turn = 6 ticket = 0

11 A lock(): gets ticket 6, runs B lock(): gets ticket 7, spins until turn=7 C lock(): gets ticket 0, spins until turn=0 6 7 A B 0 C turn = 6 ticket = 1

12 A lock(): gets ticket 6, runs B lock(): gets ticket 7, spins until turn=7 C lock(): gets ticket 0, spins until turn=0 A unlock(): turn++ B runs 6 7 B 0 C turn = 7 ticket = 1

13 A lock(): gets ticket 6, runs B lock(): gets ticket 7, spins until turn=7 C lock(): gets ticket 0, spins until turn=0 A unlock(): turn++ B runs A lock(): gets ticket 1, spins until turn= B 0 C 3 A 1 2 turn = 7 ticket = 2

14 A lock(): gets ticket 6, runs B lock(): gets ticket 7, spins until turn=7 C lock(): gets ticket 0, spins until turn=0 A unlock(): turn++ B runs A lock(): gets ticket 1, spins until turn=1 B unlock(): turn++ C runs C 3 A 1 2 turn = 0 ticket = 2

15 A lock(): gets ticket 6, runs B lock(): gets ticket 7, spins until turn=7 C lock(): gets ticket 0, spins until turn=0 A unlock(): turn++ B runs A lock(): gets ticket 1, spins until turn=1 B unlock(): turn++ C runs C unlock(): turn++ A runs A turn = 1 ticket = 2 1 2

16 A lock(): gets ticket 6, runs B lock(): gets ticket 7, spins until turn=7 C lock(): gets ticket 0, spins until turn=0 A unlock(): turn++ B runs A lock(): gets ticket 1, spins until turn=1 B unlock(): turn++ C runs C unlock(): turn++ A runs A unlock(): turn turn = 2 ticket = 2 1 2

17 A lock(): gets ticket 6, runs B lock(): gets ticket 7, spins until turn=7 C lock(): gets ticket 0, spins until turn=0 A unlock(): turn++ B runs A lock(): gets ticket 1, spins until turn=1 B unlock(): turn++ C runs C unlock(): turn++ A runs A unlock(): turn++ C lock(): gets ticket 2, runs C turn = 2 ticket = 3 1 2

18 Do it. Problem 2

19 Ticket Lock (1) typedef struct lock_t { int ticket; int turn; } void lock_init(lock_t *lock) { lock->ticket = 0; lock->turn = 0; } void acquire(lock_t *lock) { int myturn = FAA(&lock->ticket); while(lock->turn = myturn) ; // spin } void release (lock_t *lock) { FAA(&lock->turn); }

20 Ticket Lock (2) typedef struct lock_t { int ticket; int turn; } void lock_init(lock_t *lock) { lock->ticket = 0; lock->turn = 0; } void acquire(lock_t *lock) { int myturn = FAA(&lock->ticket); while(lock->turn = myturn) yield(); // spin } void release (lock_t *lock) { FAA(&lock->turn); }

21 lock unlock lock spin spin spin spin spin A B C D A B C D lock unlock lock A A B

22 lock unlock lock spin spin spin spin spin no yield: A B C D A B C D lock unlock lock yield: A A B

23 Spinlock Performance Waste Without yield: O(threads * time_slice) With yield: O(threads * context_switch)

24 Spinlock Performance Waste Without yield: O(threads * time_slice) With yield: O(threads * context_switch) So even with yield, we re slow with high contention.

25 Problem 3 Park: put thread to sleep Unpark: wakeup thread (a) This spins on guard why? (what is protected? what is not?) (b) This still spins. Why is it better than a simple spin lock? (c) In unlock, there is no setting of flag=0 when we unpark. Why? (d) What is the race-condition bug in this code?

26 Problem 3 Park: put thread to sleep Unpark: wakeup thread (a) This spins on guard why? (what is protected? what is not?) (b) This still spins. Why is it better than a simple spin lock? (c) In unlock, there is no setting of flag=0 when we unpark. Why? (d) What is the race-condition bug in this code?

27 Race Condition (2 had lock) Thread 1 Thread 2 if (lock->flag == 0) queue_push(lock->q, gettid()); lock->guard = 0; while (xchg(&lock->guard, 1) == 1) if (queue_empty(lock->q)) unpark(queue_pop(lock->q)); lock->guard = 0; park(); (in lock) (in unlock)

28 Incorrect Code void lock(lock_t *lock) { while (xchg(&lock->guard, 1) == 1) ; // spin if (lock->flag == 0) { // lock is free: grab it lock->flag = 1; lock->guard = 0; } else { // lock not free: sleep queue_push(lock->q, gettid()); lock->guard = 0; park(); // put self to sleep } } Race

29 Correct Code void lock(lock_t *lock) { while (xchg(&lock->guard, 1) == 1) ; // spin if (lock->flag == 0) { // lock is free: grab it lock->flag = 1; lock->guard = 0; } else { // lock not free: sleep queue_push(lock->q, gettid()); setpark(); lock->guard = 0; park(); // put self to sleep } }

30 Queue Lock RUNNABLE: RUNNING: WAITING: A, B, C, D <empty> <empty>

31 Queue Lock RUNNABLE: RUNNING: WAITING: B, C, D A <empty> lock A

32 Queue Lock RUNNABLE: RUNNING: WAITING: C, D, A B <empty> lock A B

33 Queue Lock RUNNABLE: C, D, A RUNNING: WAITING: lock B try lock (sleep) A B

34 Queue Lock RUNNABLE: RUNNING: WAITING: lock D, A C B try lock (sleep) A B C

35 Queue Lock RUNNABLE: RUNNING: WAITING: lock A, C D B try lock (sleep) A B C D

36 Queue Lock RUNNABLE: A, C RUNNING: WAITING: lock B, D try lock (sleep) try lock (sleep) A B C D

37 Queue Lock RUNNABLE: RUNNING: WAITING: lock C A B, D try lock (sleep) try lock (sleep) A B C D A

38 Queue Lock RUNNABLE: RUNNING: WAITING: lock A C B, D try lock (sleep) try lock (sleep) A B C D A C

39 Queue Lock RUNNABLE: RUNNING: WAITING: lock C A B, D try lock (sleep) try lock (sleep) A B C D A C A

40 Queue Lock RUNNABLE: C RUNNING: A WAITING: B, D lock try lock (sleep) try lock (sleep) unlock A B C D A C A

41 Queue Lock RUNNABLE: RUNNING: B, D, C A WAITING: lock try lock (sleep) try lock (sleep) unlock A B C D A C A

42 Queue Lock RUNNABLE: RUNNING: B, D, C A WAITING: lock try lock (sleep) try lock (sleep) unlock A B C D A C A

43 Queue Lock RUNNABLE: RUNNING: D, C, A B WAITING: lock try lock (sleep) try lock (sleep) unlock lock A B C D A C A B

44 Condition Variables

45 Concurrency Objectives Mutual exclusion (e.g., A and B don t run at same time) - solved with locks Ordering (e.g., B runs after A) - solved with condition variables

46 Ordering Example: Join pthread_t p1, p2; Pthread_create(&p1, NULL, mythread, "A"); Pthread_create(&p2, NULL, mythread, B"); // join waits for the threads to finish Pthread_join(p1, NULL); Pthread_join(p2, NULL); printf("main: done\n [balance: %d]\n [should: %d]\n", balance, max*2); return 0;

47 Ordering Example: Join pthread_t p1, p2; Pthread_create(&p1, NULL, mythread, "A"); Pthread_create(&p2, NULL, mythread, B"); // join waits for the threads to finish Pthread_join(p1, NULL); Pthread_join(p2, NULL); how to implement join? printf("main: done\n [balance: %d]\n [should: %d]\n", balance, max*2); return 0;

48 Spin Join (Bad) volatile int done = 0; void *child_func(void *arg) { do some work done = 1; } int main( ) { pthread_t child; Pthread_create( child_func ); while (ready) ; // spin printf( child is done\n ); }

49 Spin Join (Bad) volatile int done = 0; void *child_func(void *arg) { do some work done = 1; } int main( ) { pthread_t child; Pthread_create( child_func ); while (ready) really slow ; // spin printf( child is done\n ); }

50 Spin Join (Bad) volatile int done = 0; void *child_func(void *arg) { do some work done = 1; } int main( ) { pthread_t child; Pthread_create( child_func ); while (ready) ; // spin printf( child is done\n ); } want parent to sleep until done=1

51 Spin Join (Bad) volatile int done = 0; void *child_func(void *arg) { do some work done = 1; } int main( ) { pthread_t child; Pthread_create( child_func ); while (ready) ; // spin printf( child is done\n ); } want parent to sleep until done=1 need way for child to nudge parent

52 Condition Variables CVs are used to wait until a some variable meets some condition. CV s are more like channels than variables. B waits for a signal on channel before running. A sends signal when it is time for B to run. A CV also has a queue of waiting threads.

53 Broken CV s wait(cond_t *cv) - puts caller to sleep (and on queue) signal(cond_t *cv) - wake a single waiting thread (if >= 1 thread is waiting) - if there is no waiting thread, just return w/o doing anything

54 Broken CV s wait(cond_t *cv) - puts caller to sleep (and on queue) when to call? signal(cond_t *cv) - wake a single waiting thread (if >= 1 thread is waiting) - if there is no waiting thread, just return w/o doing anything

55 Parent: Way 1 if (ready) wait(&cv); lock(&mutex); // critical section unlock(&mutex);

56 Parent: Way 1 if (ready) wait(&cv); what if another thread sets ready=1 here? lock(&mutex); // critical section unlock(&mutex);

57 Parent: Way 2 lock(&mutex); // critical section if (ready) wait(&cv); unlock(&mutex);

58 Parent: Way 2 lock(&mutex); // critical section if (ready) wait(&cv); unlock(&mutex); nobody can wake us up because we hold mutex

59 Broken CV s wait(cond_t *cv) - puts caller to sleep signal(cond_t *cv) - wake a single waiting thread (if >= 1 thread is waiting) - if there is no waiting thread, just return w/o doing anything

60 Correct CV s wait(cond_t *cv, mutex_t *lock) - assumes the lock is held when wait() is called - puts caller to sleep + releases the lock (atomically) - when awoken, reacquires lock before returning signal(cond_t *cv) - wake a single waiting thread (if >= 1 thread is waiting) - if there is no waiting thread, just return w/o doing anything

61 Correct CV s wait(cond_t *cv, mutex_t *lock) - assumes the lock is held when wait() is called - puts caller to sleep + releases the lock (atomically) - when awoken, reacquires lock before returning requires kernel support signal(cond_t *cv) - wake a single waiting thread (if >= 1 thread is waiting) - if there is no waiting thread, just return w/o doing anything

62 Weird CV Behavior 1 Condition Variable wait wait thread thread

63 Weird CV Behavior 1 thread signal Condition Variable wait wait thread thread

64 Weird CV Behavior 1 Condition Variable wait thread

65 Weird CV Behavior 1 Condition Variable wait thread only one thread gets a signal

66 Weird CV Behavior 2 Condition Variable wait wait thread thread

67 Weird CV Behavior 2? signal Condition Variable wait wait thread thread

68 Weird CV Behavior 2 Condition Variable wait thread

69 Weird CV Behavior 2 Condition Variable wait thread spurious signals are possible

70 Weird CV Behavior 3 Condition Variable

71 Weird CV Behavior 3 thread signal Condition Variable

72 Weird CV Behavior 3 Condition Variable

73 Weird CV Behavior 3 Condition Variable wait thread

74 Weird CV Behavior 3 Condition Variable wait thread waits forever

75 Weird CV Behavior 3 Condition Variable wait thread waits forever signals lost if nobody waiting at that time

76 Guarantee upon signal, at least one thread will wake (if there is at least one waiting) Condition Variable wait wait thread thread

77 Guarantee upon signal, at least one thread will wake (if there is at least one waiting) thread signal Condition Variable wait wait thread thread

78 Guarantee upon signal, at least one thread will wake (if there is at least one waiting) thread signal Condition Variable wait wait thread thread

79 Guarantee upon signal, at least one thread will wake (if there is at least one waiting) Condition Variable wait thread

80 goto terminal Do code examples

81 Condition Variables in xv6 code proc.c: - sleep() is like cond_wait() - wakeup() is like cond_signal() Example use case: - piperead() and pipewrite() in pipe.c

82 Summary Need both mutual exclusion AND ordering Condition variables provide ordering.

Concurrency: Signaling and Condition Variables

Concurrency: Signaling and Condition Variables Concurrency: Signaling and Condition Variables Questions Answered in this Lecture: How do we make fair locks perform better? How do we notify threads of that some condition has been met? Hale CS450 Thanks

More information

Locks. Dongkun Shin, SKKU

Locks. Dongkun Shin, SKKU Locks 1 Locks: The Basic Idea To implement a critical section A lock variable must be declared A lock variable holds the state of the lock Available (unlocked, free) Acquired (locked, held) Exactly one

More information

Implementing Locks. Nima Honarmand (Based on slides by Prof. Andrea Arpaci-Dusseau)

Implementing Locks. Nima Honarmand (Based on slides by Prof. Andrea Arpaci-Dusseau) Implementing Locks Nima Honarmand (Based on slides by Prof. Andrea Arpaci-Dusseau) Lock Implementation Goals We evaluate lock implementations along following lines Correctness Mutual exclusion: only one

More information

Operating System Labs. Yuanbin Wu

Operating System Labs. Yuanbin Wu Operating System Labs Yuanbin Wu CS@ECNU Operating System Labs Project 4 Due: 10 Dec. Oral tests of Project 3 Date: Nov. 27 How 5min presentation 2min Q&A Operating System Labs Oral tests of Lab 3 Who

More information

Announcements. Class feedback for mid-course evaluations Receive about survey to fill out until this Friday

Announcements. Class feedback for mid-course evaluations Receive  about survey to fill out until this Friday Announcements Project 2: Part 2a will be graded this week Part 2b take longer since we compare all graphs Project 3: Shared memory segments Linux: use shmget and shmat across server + client processes

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

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

Concurrency: Mutual Exclusion (Locks)

Concurrency: Mutual Exclusion (Locks) Concurrency: Mutual Exclusion (Locks) Questions Answered in this Lecture: What are locks and how do we implement them? How do we use hardware primitives (atomics) to support efficient locks? How do we

More information

CS 537 Lecture 11 Locks

CS 537 Lecture 11 Locks CS 537 Lecture 11 Locks Michael Swift 10/17/17 2004-2007 Ed Lazowska, Hank Levy, Andrea and Remzi Arpaci-Dussea, Michael Swift 1 Concurrency: Locks Questions answered in this lecture: Review: Why threads

More information

CS 537: Introduction to Operating Systems Fall 2015: Midterm Exam #2 SOLUTIONS

CS 537: Introduction to Operating Systems Fall 2015: Midterm Exam #2 SOLUTIONS CS 537: Introduction to Operating Systems Fall 2015: Midterm Exam #2 SOLUTIONS This exam is closed book, closed notes. All cell phones must be turned off. No calculators may be used. You have two hours

More information

[537] Locks. Tyler Harter

[537] Locks. Tyler Harter [537] Locks Tyler Harter Review: Threads+Locks CPU 1 CPU 2 running thread 1 running thread 2 RAM PageDir A PageDir B CPU 1 CPU 2 running thread 1 running thread 2 RAM PageDir A PageDir B Virt Mem (PageDir

More information

Concurrency: Locks. Announcements

Concurrency: Locks. Announcements CS 537 Introduction to Operating Systems UNIVERSITY of WISCONSIN-MADISON Computer Sciences Department Concurrency: Locks Andrea C. Arpaci-Dusseau Remzi H. Arpaci-Dusseau Questions answered in this lecture:

More information

[537] Semaphores. Tyler Harter

[537] Semaphores. Tyler Harter [537] Semaphores Tyler Harter Producer/Consumer Problem Producers generate data (like pipe writers). Consumers grab data and process it (like pipe readers). Producer/consumer problems are frequent in systems.

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

CS 537: Introduction to Operating Systems (Summer 2017) University of Wisconsin-Madison Department of Computer Sciences.

CS 537: Introduction to Operating Systems (Summer 2017) University of Wisconsin-Madison Department of Computer Sciences. CS 537: Introduction to Operating Systems (Summer 2017) University of Wisconsin-Madison Department of Computer Sciences Midterm Exam 2 July 21 st, 2017 3 pm - 5 pm There are sixteen (16) total numbered

More information

Synchronization I. To do

Synchronization I. To do Synchronization I To do q Race condition, critical regions q Locks and concurrent data structures q Next time: Condition variables, semaphores and monitors Cooperating processes Cooperating processes need

More information

Synchronization I. Today. Next time. Race condition, critical regions and locks. Condition variables, semaphores and Monitors

Synchronization I. Today. Next time. Race condition, critical regions and locks. Condition variables, semaphores and Monitors Synchronization I Today Race condition, critical regions and locks Next time Condition variables, semaphores and Monitors Cooperating processes Cooperating processes need to communicate They can affect/be

More information

Synchronization I. Today. Next time. Monitors. ! Race condition, critical regions and locks. ! Condition variables, semaphores and

Synchronization I. Today. Next time. Monitors. ! Race condition, critical regions and locks. ! Condition variables, semaphores and Synchronization I Today! Race condition, critical regions and locks Next time! Condition variables, semaphores and Monitors Cooperating processes! Cooperating processes need to communicate They can affect/be

More information

TCSS 422: OPERATING SYSTEMS

TCSS 422: OPERATING SYSTEMS TCSS 422: OPERATING SYSTEMS OBJECTIVES Introduction to threads Concurrency: An Introduction Wes J. Lloyd Institute of Technology University of Washington - Tacoma Race condition Critical section Thread

More information

Systèmes d Exploitation Avancés

Systèmes d Exploitation Avancés Systèmes d Exploitation Avancés Instructor: Pablo Oliveira ISTY Instructor: Pablo Oliveira (ISTY) Systèmes d Exploitation Avancés 1 / 32 Review : Thread package API tid thread create (void (*fn) (void

More information

28. Locks. Operating System: Three Easy Pieces

28. Locks. Operating System: Three Easy Pieces 28. Locks Oerating System: Three Easy Pieces AOS@UC 1 Locks: The Basic Idea Ensure that any critical section executes as if it were a single atomic instruction. w An examle: the canonical udate of a shared

More information

recap, what s the problem Locks and semaphores Total Store Order Peterson s algorithm Johan Montelius 0 0 a = 1 b = 1 read b read a

recap, what s the problem Locks and semaphores Total Store Order Peterson s algorithm Johan Montelius 0 0 a = 1 b = 1 read b read a recap, what s the problem Locks and semaphores Johan Montelius KTH 2017 # include < pthread.h> volatile int count = 0; void * hello ( void * arg ) { for ( int i = 0; i < 10; i ++) { count ++; int main

More information

FINE-GRAINED SYNCHRONIZATION. Operating Systems Engineering. Sleep & Wakeup [chapter #5] 15-Jun-14. in the previous lecture.

FINE-GRAINED SYNCHRONIZATION. Operating Systems Engineering. Sleep & Wakeup [chapter #5] 15-Jun-14. in the previous lecture. Operating Systems Engineering Sleep & Wakeup [chapter #5] By Dan Tsafrir, 2014-04-02 1 in the previous lecture. When critical section is very short FINE-GRAINED SYNCHRONIZATION 2 1 in this lecture. When

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

TCSS 422: OPERATING SYSTEMS

TCSS 422: OPERATING SYSTEMS TCSS 422: OPERATING SYSTEMS Concurrency: An Introduction Wes J. Lloyd Institute of Technology University of Washington - Tacoma FEEDBACK FROM 1/23 Are there larger overhead costs for any particular type

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

Synchronization I q Race condition, critical regions q Locks and concurrent data structures q Next time: Condition variables, semaphores and monitors

Synchronization I q Race condition, critical regions q Locks and concurrent data structures q Next time: Condition variables, semaphores and monitors Synchronization I q Race condition, critical regions q Locks and concurrent data structures q Next time: Condition variables, semaphores and monitors Cooperating processes and threads Cooperating processes

More information

Locks and semaphores. Johan Montelius KTH

Locks and semaphores. Johan Montelius KTH Locks and semaphores Johan Montelius KTH 2018 1 / 40 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

CS 111. Operating Systems Peter Reiher

CS 111. Operating Systems Peter Reiher Operating System Principles: Mutual Exclusion and Asynchronous Completion Operating Systems Peter Reiher Page 1 Outline Mutual Exclusion Asynchronous Completions Page 2 Mutual Exclusion Critical sections

More information

CONCURRENCY: DEADLOCK. Shivaram Venkataraman CS 537, Spring 2019

CONCURRENCY: DEADLOCK. Shivaram Venkataraman CS 537, Spring 2019 CONCURRENCY: DEADLOCK Shivaram Venkataraman CS 537, Spring 2019 ADMINISTRIVIA Midterm is on Wednesday 3/13 at 5.15pm, details on Piazza Venue: If your last name starts with A-L, go to VanVleck B102 else

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

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

Learning Outcomes. Concurrency and Synchronisation. Textbook. Concurrency Example. Inter- Thread and Process Communication. Sections & 2.

Learning Outcomes. Concurrency and Synchronisation. Textbook. Concurrency Example. Inter- Thread and Process Communication. Sections & 2. Learning Outcomes Concurrency and Synchronisation Understand concurrency is an issue in operating systems and multithreaded applications Know the concept of a critical region. Understand how mutual exclusion

More information

Concurrency and Synchronisation

Concurrency and Synchronisation Concurrency and Synchronisation 1 Sections 2.3 & 2.4 Textbook 2 Making Single-Threaded Code Multithreaded Conflicts between threads over the use of a global variable 3 Inter- Thread and Process Communication

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

Concurrency and Synchronisation

Concurrency and Synchronisation Concurrency and Synchronisation 1 Learning Outcomes Understand concurrency is an issue in operating systems and multithreaded applications Know the concept of a critical region. Understand how mutual exclusion

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

Condition Variables. Dongkun Shin, SKKU

Condition Variables. Dongkun Shin, SKKU Condition Variables 1 Why Condition? cases where a thread wishes to check whether a condition is true before continuing its execution 1 void *child(void *arg) { 2 printf("child\n"); 3 // XXX how to indicate

More information

C09: Process Synchronization

C09: Process Synchronization CISC 7310X C09: Process Synchronization Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/29/2018 CUNY Brooklyn College 1 Outline Race condition and critical regions The bounded

More information

Condition Variables. Dongkun Shin, SKKU

Condition Variables. Dongkun Shin, SKKU Condition Variables 1 Why Condition? cases where a thread wishes to check whether a condition is true before continuing its execution 1 void *child(void *arg) { 2 printf("child\n"); 3 // XXX how to indicate

More information

Threads. Concurrency. What it is. Lecture Notes Week 2. Figure 1: Multi-Threading. Figure 2: Multi-Threading

Threads. Concurrency. What it is. Lecture Notes Week 2. Figure 1: Multi-Threading. Figure 2: Multi-Threading Threads Figure 1: Multi-Threading Figure 2: Multi-Threading Concurrency What it is 1. Two or more threads of control access a shared resource. Scheduler operation must be taken into account fetch-decode-execute-check

More information

Review: Processes. A process is an instance of a running program. POSIX Thread APIs:

Review: Processes. A process is an instance of a running program. POSIX Thread APIs: Review: Processes A process is an instance of a running program - A thread is an execution context - Process can have one or more threads - Threads share address space (code, data, heap), open files -

More information

Administrivia. Review: Thread package API. Program B. Program A. Program C. Correct answers. Please ask questions on Google group

Administrivia. Review: Thread package API. Program B. Program A. Program C. Correct answers. Please ask questions on Google group Administrivia Please ask questions on Google group - We ve had several questions that would likely be of interest to more students x86 manuals linked on reference materials page Next week, guest lecturer:

More information

10/17/ Gribble, Lazowska, Levy, Zahorjan 2. 10/17/ Gribble, Lazowska, Levy, Zahorjan 4

10/17/ Gribble, Lazowska, Levy, Zahorjan 2. 10/17/ Gribble, Lazowska, Levy, Zahorjan 4 Temporal relations CSE 451: Operating Systems Autumn 2010 Module 7 Synchronization Instructions executed by a single thread are totally ordered A < B < C < Absent synchronization, instructions executed

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

As an example, assume our critical section looks like this, the canonical update of a shared variable:

As an example, assume our critical section looks like this, the canonical update of a shared variable: 27 Locks From the introduction to concurrency, we saw one of the fundamental problems in concurrent programming: we would like to execute a series of instructions atomically, but due to the presence of

More information

Synchronization I. Jo, Heeseung

Synchronization I. Jo, Heeseung Synchronization I Jo, Heeseung Today's Topics Synchronization problem Locks 2 Synchronization Threads cooperate in multithreaded programs To share resources, access shared data structures Also, to coordinate

More information

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Steve Gribble. Synchronization. Threads cooperate in multithreaded programs

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Steve Gribble. Synchronization. Threads cooperate in multithreaded programs CSE 451: Operating Systems Winter 2005 Lecture 7 Synchronization Steve Gribble Synchronization Threads cooperate in multithreaded programs to share resources, access shared data structures e.g., threads

More information

Lecture 5: Synchronization w/locks

Lecture 5: Synchronization w/locks Lecture 5: Synchronization w/locks CSE 120: Principles of Operating Systems Alex C. Snoeren Lab 1 Due 10/19 Threads Are Made to Share Global variables and static objects are shared Stored in the static

More information

Multiprocessors and Locking

Multiprocessors and Locking Types of Multiprocessors (MPs) Uniform memory-access (UMA) MP Access to all memory occurs at the same speed for all processors. Multiprocessors and Locking COMP9242 2008/S2 Week 12 Part 1 Non-uniform memory-access

More information

Synchronization II. q Condition Variables q Semaphores and monitors q Some classical problems q Next time: Deadlocks

Synchronization II. q Condition Variables q Semaphores and monitors q Some classical problems q Next time: Deadlocks Synchronization II q Condition Variables q Semaphores and monitors q Some classical problems q Next time: Deadlocks Condition variables Locks are not enough to build concurrent programs Many times a thread

More information

Review: Thread package API

Review: Thread package API Review: Thread package API tid thread_create (void (*fn) (void *), void *arg); - Create a new thread that calls fn with arg void thread_exit (); void thread_join (tid thread); The execution of multiple

More information

Review: Thread package API

Review: Thread package API Review: Thread package API tid thread create (void (*fn) (void *), void *arg); - Create a new thread that calls fn with arg void thread exit (); void thread join (tid thread); The execution of multiple

More information

Concurrency, Thread. Dongkun Shin, SKKU

Concurrency, Thread. Dongkun Shin, SKKU Concurrency, Thread 1 Thread Classic view a single point of execution within a program a single PC where instructions are being fetched from and executed), Multi-threaded program Has more than one point

More information

OS Structure. User mode/ kernel mode (Dual-Mode) Memory protection, privileged instructions. Definition, examples, how it works?

OS Structure. User mode/ kernel mode (Dual-Mode) Memory protection, privileged instructions. Definition, examples, how it works? Midterm Review OS Structure User mode/ kernel mode (Dual-Mode) Memory protection, privileged instructions System call Definition, examples, how it works? Other concepts to know Monolithic kernel vs. Micro

More information

Process & Thread Management II. Queues. Sleep() and Sleep Queues CIS 657

Process & Thread Management II. Queues. Sleep() and Sleep Queues CIS 657 Process & Thread Management II CIS 657 Queues Run queues: hold threads ready to execute Not a single ready queue; 64 queues All threads in same queue are treated as same priority Sleep queues: hold threads

More information

Process & Thread Management II CIS 657

Process & Thread Management II CIS 657 Process & Thread Management II CIS 657 Queues Run queues: hold threads ready to execute Not a single ready queue; 64 queues All threads in same queue are treated as same priority Sleep queues: hold threads

More information

CS 111. Operating Systems Peter Reiher

CS 111. Operating Systems Peter Reiher Operating System Principles: Mutual Exclusion and Asynchronous Completion Operating Systems Peter Reiher Page 1 Outline Mutual Exclusion Asynchronous Completions Page 2 Mutual Exclusion Critical sections

More information

Chapter 6: Process Synchronization

Chapter 6: Process Synchronization Chapter 6: Process Synchronization Objectives Introduce Concept of Critical-Section Problem Hardware and Software Solutions of Critical-Section Problem Concept of Atomic Transaction Operating Systems CS

More information

OS Structure. User mode/ kernel mode. System call. Other concepts to know. Memory protection, privileged instructions

OS Structure. User mode/ kernel mode. System call. Other concepts to know. Memory protection, privileged instructions Midterm Review OS Structure User mode/ kernel mode Memory protection, privileged instructions System call Definition, examples, how it works? Other concepts to know Monolithic kernel vs. Micro kernel 2

More information

Concurrency and Synchronisation. Leonid Ryzhyk

Concurrency and Synchronisation. Leonid Ryzhyk Concurrency and Synchronisation Leonid Ryzhyk Textbook Sections 2.3 & 2.5 2 Concurrency in operating systems Inter-process communication web server SQL request DB Intra-process communication worker thread

More information

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Hank Levy 412 Sieg Hall

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Hank Levy 412 Sieg Hall CSE 451: Operating Systems Winter 2003 Lecture 7 Synchronization Hank Levy Levy@cs.washington.edu 412 Sieg Hall Synchronization Threads cooperate in multithreaded programs to share resources, access shared

More information

Chap. 6 Part 1. CIS*3090 Fall Fall 2016 CIS*3090 Parallel Programming 1

Chap. 6 Part 1. CIS*3090 Fall Fall 2016 CIS*3090 Parallel Programming 1 Chap. 6 Part 1 CIS*3090 Fall 2016 Fall 2016 CIS*3090 Parallel Programming 1 Chap 6: specific programming techniques Languages and libraries Authors blur the distinction Languages: access parallel programming

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

Review: Thread package API

Review: Thread package API 1/39 Review: Thread package API tid thread create (void (*fn) (void *), void *arg); - Create a new thread that callsfn witharg void thread exit (); void thread join (tid thread); The execution of multiple

More information

Operating Systems. Synchronization

Operating Systems. Synchronization Operating Systems Fall 2014 Synchronization Myungjin Lee myungjin.lee@ed.ac.uk 1 Temporal relations Instructions executed by a single thread are totally ordered A < B < C < Absent synchronization, instructions

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

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

Synchronization. Disclaimer: some slides are adopted from the book authors slides with permission 1 Synchronization Disclaimer: some slides are adopted from the book authors slides with permission 1 What is it? Recap: Thread Independent flow of control What does it need (thread private)? Stack What for?

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

Synchronization II. Today. ! Condition Variables! Semaphores! Monitors! and some classical problems Next time. ! Deadlocks

Synchronization II. Today. ! Condition Variables! Semaphores! Monitors! and some classical problems Next time. ! Deadlocks Synchronization II Today Condition Variables Semaphores Monitors and some classical problems Next time Deadlocks Condition variables Many times a thread wants to check whether a condition is true before

More information

[537] Concurrency Bugs. Tyler Harter

[537] Concurrency Bugs. Tyler Harter [537] Concurrency Bugs Tyler Harter Review Semaphores CV s vs. Semaphores CV rules of thumb: - Keep state in addition to CV s - Always do wait/signal with lock held - Whenever you acquire a lock, recheck

More information

Program A. Review: Thread package API. Program B. Program C. Correct answers. Correct answers. Q: Can both critical sections run?

Program A. Review: Thread package API. Program B. Program C. Correct answers. Correct answers. Q: Can both critical sections run? Review: Thread package API tid thread_create (void (*fn) (void *), void *arg); - Create a new thread that calls fn with arg void thread_exit (); void thread_join (tid thread); The execution of multiple

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

Why We Wait. Mutual Exclusion, Async Completions. Correct Ordering. Approaches to Waiting. Condition Variables 4/15/2017

Why We Wait. Mutual Exclusion, Async Completions. Correct Ordering. Approaches to Waiting. Condition Variables 4/15/2017 Mutual Exclusion, Async Completions 7C. Asynchronous Event Completions 7D. Mutual Exclusion 7E. Implementing Mutual Exclusion 7F. Asynchronous completion operations 7G. Implementing Asynchronous Completion

More information

Background. Old Producer Process Code. Improving the Bounded Buffer. Old Consumer Process Code

Background. Old Producer Process Code. Improving the Bounded Buffer. Old Consumer Process Code Old Producer Process Code Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure the orderly execution of cooperating processes Our

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

User Space Multithreading. Computer Science, University of Warwick

User Space Multithreading. Computer Science, University of Warwick User Space Multithreading 1 Threads Thread short for thread of execution/control B efore create Global During create Global Data Data Executing Code Code Stack Stack Stack A fter create Global Data Executing

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

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

Synchronization I. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University Synchronization I Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Today s Topics Synchronization problem Locks 2 Synchronization Threads cooperate

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

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

Condition Variables. Figure 29.1: A Parent Waiting For Its Child

Condition Variables. Figure 29.1: A Parent Waiting For Its Child 29 Condition Variables Thus far we have developed the notion of a lock and seen how one can be properly built with the right combination of hardware and OS support. Unfortunately, locks are not the only

More information

Operating Systems. Lab. Class Week 14

Operating Systems. Lab. Class Week 14 Operating Systems Lab. Class Week 14 Project Plan 6 projects 0. Install xv6 1. System call 2. Scheduling 3. Virtual memory 1 4. Virtual memory 2 5. Concurrency 1 6. Concurrency 2 Individual projects 2016-06-01

More information

Why We Wait. IPC, Threads, Races, Critical Sections. Correct Ordering. Approaches to Waiting. Condition Variables 4/23/2018

Why We Wait. IPC, Threads, Races, Critical Sections. Correct Ordering. Approaches to Waiting. Condition Variables 4/23/2018 7C. Asynchronous Event Completion 7D. Mutual Exclusion 7E. 7F. Asynchronous completion 7G. Implementing asynchronous completion Why We Wait We await completion of non-trivial operations data to be read

More information

LAB 2: PROCESS SYNCHRONIZATION IN XV6

LAB 2: PROCESS SYNCHRONIZATION IN XV6 Fall 2018 - CS/COE 1550 LAB 2: PROCESS SYNCHRONIZATION IN XV6 In this lab, you will implement a synchronization solution using locks and condition variables to guarantee a specific execution ordering among

More information

THREADS: (abstract CPUs)

THREADS: (abstract CPUs) CS 61 Scribe Notes (November 29, 2012) Mu, Nagler, Strominger TODAY: Threads, Synchronization - Pset 5! AT LONG LAST! Adversarial network pong handling dropped packets, server delays, overloads with connection

More information

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

Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective? Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective? CS 470 Spring 2019 POSIX Mike Lam, Professor Multithreading & Pthreads MIMD

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

Condition Variables. parent: begin child parent: end

Condition Variables. parent: begin child parent: end 22 Condition Variables Thus far we have developed the notion of a lock and seen how one can be properly built with the right combination of hardware and OS support. Unfortunately, locks are not the only

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

Background. The Critical-Section Problem Synchronisation Hardware Inefficient Spinning Semaphores Semaphore Examples Scheduling.

Background. The Critical-Section Problem Synchronisation Hardware Inefficient Spinning Semaphores Semaphore Examples Scheduling. Background The Critical-Section Problem Background Race Conditions Solution Criteria to Critical-Section Problem Peterson s (Software) Solution Concurrent access to shared data may result in data inconsistency

More information

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox Concurrency & Synchronization COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox Midterm Review http://www.cs.duke.edu/~chase/cps11 0-archive/midterm-210-13s1.pdf Please

More information

CPS 310 first midterm exam, 10/6/2014

CPS 310 first midterm exam, 10/6/2014 CPS 310 first midterm exam, 10/6/2014 Your name please: Part 1. More fun with fork and exec* What is the output generated by this program? Please assume that each executed print statement completes, e.g.,

More information

CS 153 Design of Operating Systems Winter 2016

CS 153 Design of Operating Systems Winter 2016 CS 153 Design of Operating Systems Winter 2016 Lecture 9: Semaphores and Monitors Some slides from Matt Welsh Summarize Where We Are Goal: Use mutual exclusion to protect critical sections of code that

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

Lecture 9: Multiprocessor OSs & Synchronization. CSC 469H1F Fall 2006 Angela Demke Brown

Lecture 9: Multiprocessor OSs & Synchronization. CSC 469H1F Fall 2006 Angela Demke Brown Lecture 9: Multiprocessor OSs & Synchronization CSC 469H1F Fall 2006 Angela Demke Brown The Problem Coordinated management of shared resources Resources may be accessed by multiple threads Need to control

More information

Operating Systems, Assignment 2 Threads and Synchronization

Operating Systems, Assignment 2 Threads and Synchronization Operating Systems, Assignment 2 Threads and Synchronization Responsible TA's: Zohar and Matan Assignment overview The assignment consists of the following parts: 1) Kernel-level threads package 2) Synchronization

More information

As an example, assume our critical section looks like this, the canonical update of a shared variable:

As an example, assume our critical section looks like this, the canonical update of a shared variable: 28 Locks From the introduction to concurrency, we saw one of the fundamental problems in concurrent programming: we would like to execute a series of instructions atomically, but due to the presence of

More information

EEE3052: Introduction to Operating Systems. Fall Project #3

EEE3052: Introduction to Operating Systems. Fall Project #3 EEE3052: Introduction to Operating Systems Fall 2017 Project #3 Project Plan 4 projects 0) Install Xv6 1) Process management 2) Virtual memory 3) Synchronization - Thread (11/13 ~ 11/21) - Mutex & Condition

More information

! Why is synchronization needed? ! Synchronization Language/Definitions: ! How are locks implemented? Maria Hybinette, UGA

! Why is synchronization needed? ! Synchronization Language/Definitions: ! How are locks implemented? Maria Hybinette, UGA Chapter 6: Process [& Thread] Synchronization CSCI [4 6] 730 Operating Systems Synchronization Part 1 : The Basics! Why is synchronization needed?! Synchronization Language/Definitions:» What are race

More information