CS 470 Spring Mike Lam, Professor. Semaphores and Conditions

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

Synchronization Mechanisms

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017

W4118 Operating Systems. Instructor: Junfeng Yang

Synchroniza+on II COMS W4118

Week 3. Locks & Semaphores

Condition Variables. Dongkun Shin, SKKU

Synchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1

Multithreading Programming II

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

Synchronization. Semaphores implementation

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

Condition Variables. Dongkun Shin, SKKU

Operating Systems (2INC0) 2017/18

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

CS 153 Lab6. Kishore Kumar Pusukuri

Synchronization. Dr. Yingwu Zhu

CSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks

Synchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1

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

Process Synchronization

CS 31: Intro to Systems Misc. Threading. Kevin Webb Swarthmore College December 6, 2018

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

CS 220: Introduction to Parallel Computing. Condition Variables. Lecture 24

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

Locks and semaphores. Johan Montelius KTH

More Types of Synchronization 11/29/16

Process Synchronization (Part I)

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

Condition Variables. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

CIS Operating Systems Application of Semaphores. Professor Qiang Zeng Spring 2018

POSIX Threads. HUJI Spring 2011

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

Synchronization Primitives

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

CS 470 Spring Mike Lam, Professor. Advanced OpenMP

PRINCIPLES OF OPERATING SYSTEMS

EEE3052: Introduction to Operating Systems. Fall Project #3

CS 470 Spring Mike Lam, Professor. Advanced OpenMP

CS 537 Lecture 8 Monitors. Thread Join with Semaphores. Dining Philosophers. Parent thread. Child thread. Michael Swift

Introduction to parallel computing

Locks and semaphores. Johan Montelius KTH

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

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

Synchronization (Part 2) 1/40

More Shared Memory Programming

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

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

Concurrent Programming Lecture 10

Lecture 9: Thread Synchronizations. Spring 2016 Jason Tang

POSIX Threads. Paolo Burgio

Motivation and definitions Processes Threads Synchronization constructs Speedup issues

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

Process Synchronization(2)

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Paralleland Distributed Programming. Concurrency

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

Using Semaphores CS 241. March 14, University of Illinois

real time operating systems course

Shared Memory Programming. Parallel Programming Overview

ANSI/IEEE POSIX Standard Thread management

Lecture 4. Threads vs. Processes. fork() Threads. Pthreads. Threads in C. Thread Programming January 21, 2005

Atomic Instructions! Hakim Weatherspoon CS 3410, Spring 2011 Computer Science Cornell University. P&H Chapter 2.11

Lecture Outline. CS 5523 Operating Systems: Concurrency and Synchronization. a = 0; b = 0; // Initial state Thread 1. Objectives.

Operating systems and concurrency (B08)

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

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

CMSC421: Principles of Operating Systems

Process Synchronization(2)

Systems Programming/ C and UNIX

Project 3-2. Mutex & CV

Condition Variables & Semaphores

Operating systems. Lecture 3 Interprocess communication. Narcis ILISEI, 2018

Dining Philosophers, Semaphores

Thread Posix: Condition Variables Algoritmi, Strutture Dati e Calcolo Parallelo. Daniele Loiacono

Shared Memory: Virtual Shared Memory, Threads & OpenMP

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Synchronising Threads

POSIX / System Programming

CS 345 Operating Systems. Tutorial 2: Treasure Room Simulation Threads, Shared Memory, Synchronization

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

Solving the Producer Consumer Problem with PThreads

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

TCSS 422: OPERATING SYSTEMS

Plan. Demos. Next Project. CSCI [4 6]730 Operating Systems. Hardware Primitives. Process Synchronization Part II. Synchronization Part 2

Lecture 19: Shared Memory & Synchronization

Achieving Synchronization or How to Build a Semaphore

Chapter 6: Process Synchronization

Synchronization II: EventBarrier, Monitor, and a Semaphore. COMPSCI210 Recitation 4th Mar 2013 Vamsi Thummala

Process Synchronization(2)

30. Condition Variables

[537] Semaphores. Tyler Harter

PThreads in a Nutshell

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Process Synchronization

Lecture 8: September 30

Report on the Programming Language X10. Draft January 13, , Harlow, England, Addison-Wesley, Pearson education, ISBN-

Posix Threads (Pthreads)

POSIX Condition Variables ADT

Transcription:

CS 470 Spring 2018 Mike Lam, Professor Semaphores and Conditions

Synchronization mechanisms Busy-waiting (wasteful!) Atomic instructions (e.g., LOCK prefix in x86) Pthreads Mutex: simple mutual exclusion ( lock ) Condition variable: lock + wait set (wait/signal/broadcast) Semaphore: access to limited resources Not technically part of Pthreads library (just the POSIX standard) Barrier: ensure all threads are at the same point Not present in all implementations (requires --std=gnu99 on cluster) Java threads Synchronized keyword: implicit mutex Monitor: lock on object (wait/notify/notifyall)

Semaphores sem_init (sem_t*, pshared, int value) Initialize a semaphore to value sem_wait (sem_t*) If value > 0, decrement value and return Else, block until signaled sem_post (sem_t*) Increment value and signal a blocked thread Use a loop to signal multiple blocked threads sem_getvalue (sem_t*, int*) Return current value sem_destroy (sem_t*) Clean up a semaphore

Condition variables pthread_cond_init (pthread_cond_t*, attrs) Initialize a condition variable pthread_cond_wait (pthread_cond_t*, pthread_mutex_t*) Release mutex and block until signaled Re-acquires mutex after waking up A variant also exists that times out after a certain period pthread_cond_signal (pthread_cond_t*) Wake a single blocked thread pthread_cond_broadcast (pthread_cond_t*) Wake all blocked threads pthread_cond_destroy (pthread_cond_t*) Clean up a condition variable

Barrier w/ semaphores Setup: sem_t count_sem; // initialize to 1 sem_t barrier_sem; // initialize to 0 volatile int waiting_threads = 0; Threads: sem_wait(&count_sem); waiting_threads++; if (waiting_threads == thread_count) { waiting_threads = 0; sem_post(&count_sem); for (int i = 0; i < thread_count-1; i++) { sem_post(&barrier_sem); else { sem_post(&count_sem); sem_wait(&barrier_sem);

Barrier w/ condition variable Setup: mutex_t count_mut; cond_t done_waiting; volatile int waiting_threads = 0; Threads: mutex_lock(&count_mut); waiting_threads++; if (waiting_threads == thread_count) { waiting_threads = 0; cond_broadcast(&done_waiting); else { cond_wait(&done_waiting, &count_mut); mutex_unlock(&count_mut);

Barrier comparison Setup: sem_t count_sem; // initialize to 1 sem_t barrier_sem; // initialize to 0 volatile int waiting_threads = 0; Threads: Semaphores sem_wait(&count_sem); waiting_threads++; if (waiting_threads == thread_count) { waiting_threads = 0; sem_post(&count_sem); for (int i = 0; i < thread_count-1; i++) { sem_post(&barrier_sem); else { sem_post(&count_sem); sem_wait(&barrier_sem); Setup: mutex_t count_mut; cond_t done_waiting; volatile int waiting_threads = 0; Threads: Condition mutex_lock(&count_mut); waiting_threads++; if (waiting_threads == thread_count) { waiting_threads = 0; cond_broadcast(&done_waiting); else { cond_wait(&done_waiting, &count_mut); mutex_unlock(&count_mut); Barrier Setup: barrier_t barrier; // initialize to nthreads Threads: barrier_wait(&barrier);

Condition variables Issue: POSIX standard says that pthread_cond_wait might experience spurious wakeups Goal: optimize runtime and force programmers to write correct code Return value will be non-zero for such a wakeup Issue: non-determinism! Every condition should have an associated boolean predicate The predicate should be true before condition is signaled e.g., waiting_threads == nthreads Waiting thread should re-check predicate after waking up Another thread may have invalidated it in the meantime! Best practice: use a predicate loop AND zero check while (!predicate) { while (pthread_cond_wait(&cond, &mut)!= 0);

Condition variables Setup (static): pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; volatile boolean status = false; // protected by mutex Thread 1: pthread_mutex_lock(&mutex); while (!status) { while (pthread_cond_wait(&cond, &mutex)!= 0); // at this point, status == true and mutex is locked Thread 2: // do something that triggers status pthread_mutex_lock(&mutex); status = true; pthread_cond_signal(&cond); // or pthread_cond_broadcast pthread_mutex_unlock(&mutex);

Condition variables Setup (static): initializer macros; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; can be used if you pthread_cond_t cond = PTHREAD_COND_INITIALIZER; don t need attributes volatile boolean status = false; // protected by mutex Thread 1: pthread_mutex_lock(&mutex); while (!status) { check predicate again! while (pthread_cond_wait(&cond, &mutex)!= 0); // at this point, status == true and mutex is locked Thread 2: C keyword meaning don t optimize this variable; it could change at any time // do something that triggers status pthread_mutex_lock(&mutex); status = true; set predicate pthread_cond_signal(&cond); // or pthread_cond_broadcast pthread_mutex_unlock(&mutex); always acquire lock before wait, signal, or broadcast

Error checking All threading calls might return a non-zero value This generally indicates an error (except for cond_wait) Recovering from errors is not our primary concern now Although we ll talk a bit about fault tolerance later this semester For now, just write a wrapper to abort on error Example: void lock(pthread_mutex_t *mut) { if (pthread_mutex_lock(mut)!= 0) { printf("error: could not acquire mutex\n"); exit(exit_failure);

Master/worker model Common pattern: master/worker threads Original master thread creates multiple worker threads Each worker thread does a chunk of the work Coordinate via shared global data structure w/ locking Main thread waits for workers, then aggregates results master workers create join

Thread pool model (P1) Minor tweak on master/worker: thread pool model Master thread creates multiple worker threads Work queue tracks chunks of work to be done Producer/consumer: master enqueues, workers dequeue Synchronization required Workers idle while queue is empty master workers worker master worker work queue worker

P1 pseudocode master: done = false initialize work queue and sync variables spawn workers and wait for all threads to initialize for each (action, num) pair in input: if action == 'p': add num to work queue wake an idle worker thread else if action == 'w': wait num seconds worker: while not done: if queue is not empty: extract num from work queue update(num) else: block until signaled wait until all work has been processed done = true wake all worker threads and wait for them to terminate print results, clean up, and exit ONE POSSIBILITY; NOT THE ONLY SOLUTION!