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

Similar documents
Synchronization. Dr. Yingwu Zhu

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

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

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

CS510 Operating System Foundations. Jonathan Walpole

LSN 13 Linux Concurrency Mechanisms

Introduction to PThreads and Basic Synchronization

Process Synchronization

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

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

Shared Memory: Virtual Shared Memory, Threads & OpenMP

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

C Grundlagen - Threads

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

Synchronization Primitives

CS345 Opera,ng Systems. Φροντιστήριο Άσκησης 2

CS533 Concepts of Operating Systems. Jonathan Walpole

CS333 Intro to Operating Systems. Jonathan Walpole

POSIX Threads. Paolo Burgio

Thread and Synchronization

CS510 Operating System Foundations. Jonathan Walpole

real time operating systems course

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

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

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

Programming with Shared Memory. Nguyễn Quang Hùng

POSIX / System Programming

POSIX PTHREADS PROGRAMMING

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

Concurrent Server Design Multiple- vs. Single-Thread

Chapter 4 Concurrent Programming

TCSS 422: OPERATING SYSTEMS

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

CSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks

Multithreading Programming II

CS 153 Lab4 and 5. Kishore Kumar Pusukuri. Kishore Kumar Pusukuri CS 153 Lab4 and 5

CSE 421/521 - Operating Systems Fall 2011 Recitations. Recitation - III Networking & Concurrent Programming Prof. Tevfik Kosar. Presented by...

Parallel Programming with Threads

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

HPCSE - I. «Introduction to multithreading» Panos Hadjidoukas

Synchronization. Semaphores implementation

Preview. What are Pthreads? The Thread ID. The Thread ID. The thread Creation. The thread Creation 10/25/2017

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

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

Week 3. Locks & Semaphores

Posix Threads (Pthreads)

Programming in Parallel COMP755

pthreads CS449 Fall 2017

POSIX Threads. HUJI Spring 2011

CS 3305 Intro to Threads. Lecture 6

CSCI4430 Data Communication and Computer Networks. Pthread Programming. ZHANG, Mi Jan. 26, 2017

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

Synchronization: Advanced

Shared Memory Parallel Programming with Pthreads An overview

Threads. Threads (continued)

Locks and semaphores. Johan Montelius KTH

Sistemi in tempo reale

More Shared Memory Programming

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

High Performance Computing Course Notes Shared Memory Parallel Programming

Roadmap. Concurrent Programming. Concurrent Programming. Communication Between Tasks. Motivation. Tevfik Ko!ar

CSC Systems Programming Fall Lecture - XVIII Concurrent Programming. Tevfik Ko!ar. Louisiana State University. November 11 th, 2008

Multicore and Multiprocessor Systems: Part I

ANSI/IEEE POSIX Standard Thread management

ECE 598 Advanced Operating Systems Lecture 23

High Performance Computing Lecture 21. Matthew Jacob Indian Institute of Science

Lecture 9: Thread Synchronizations. Spring 2016 Jason Tang

Linux Programming

EPL372 Lab Exercise 2: Threads and pthreads. Εργαστήριο 2. Πέτρος Παναγή

Pthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Lecture 19: Shared Memory & Synchronization

Synchronization: Basics

CS 261 Fall Mike Lam, Professor. Threads

Locks and semaphores. Johan Montelius KTH

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

User Space Multithreading. Computer Science, University of Warwick

CS444 1/28/05. Lab 03

Synchronising Threads

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

CMSC421: Principles of Operating Systems

CSci 4061 Introduction to Operating Systems. (Threads-POSIX)

ENCM 501 Winter 2019 Assignment 9

Shared Memory Programming with Pthreads. T. Yang. UCSB CS240A.

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

Agenda. Process vs Thread. ! POSIX Threads Programming. Picture source:

POSIX threads CS 241. February 17, Copyright University of Illinois CS 241 Staff

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

Operating Systems, Final exam May 2016 Bachelor's Degree in Computer Science and Engineering

Unix. Threads & Concurrency. Erick Fredj Computer Science The Jerusalem College of Technology

Lecture 5 Threads and Pthreads II

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

CS240: Programming in C. Lecture 18: PThreads

dbug User Manual Computer Science Department Carnegie Mellon University

Threads Tuesday, September 28, :37 AM

CS 3723 Operating Systems: Final Review

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:

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

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

Threaded Programming. Lecture 9: Alternatives to OpenMP

TCSS 422: OPERATING SYSTEMS

Transcription:

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

Content Concurrency Concurrent Programming Thread vs. Process POSIX Threads Synchronization and Critical Sections Mutexes Semaphores

Concurrency Concurrency is a property where multiple paths of execution are running simultaneously Multiple processes/threads running on a single processor Multiple processes/threads running on multiple processors/machines (true concurrency) Requires a different programming paradigm: Concurrent programming

Concurrent Programming A programming paradigm that involves designing programs so that they can run in parallel Concurrent programs can share data and resources Two mechanisms of communication among concurrent components: Message passing Shared memory

Concurrent Programming (Cont.) Main challenges of concurrent programming: Ensuring correct and meaningful order of execution Coordinating access to shared data and resources to ensure their consistency throughout execution

Thread vs. Process A thread is a mechanim to allow a program to run things in parallel (like processes) A thread is a finer-grained unit of execution than a process. Each running process has at least one thread Each process has its own memory space, variables etc. Threads in a process share the same memory space, variables etc.

POSIX Threads POSIX (Portable Operating System Interface) is a group of standards for compatability among different operating systems POSIX Threads (pthreads) is a standard for creating and using threads We will use the GNU/Linux implementation of the pthreads

Thread Creation We will mainly use three functions: pthread create, pthread join and pthread cancel We use the pthread create to create a new thread, it takes four parameters as follows: A pointer to pthread t variable which stores the thread ID A pointer to a thread attribute object which specifies how the thread interacts with the program, or a NULL value Pointer to the function the thread will execute. The function must have a return type void* and takes void* as a parameter A thread argument value of type void* or NULL value

Thread Creation (Cont.) #include <pthread.h> #include <stdio.h> void* print_func (void* args) int count; int i; count = *(int *) args; for (i = 0; i < count; ++i) fprintf (stdout, "Hello world!\n"); return NULL; } int main (int argc, char **argv) pthread_t thread_id; int count; int i; count = 10000; pthread_create (&thread_id, NULL, &print_func, (void*) &count); pthread_join (thread_id, NULL); return 0; }

Thread Creation (Cont.) We use the pthread join to ensure that the thread executing main will wait for the other thread to finish This ensures that the created thread will no be using deallocated variables

Thread Cancellation One thread can request the termination of another thread by calling pthread cancel, passing the thread ID as an argument A thread can have one of three different cancellation states: Asynchronously cancelable Synchronously cancelable Uncancelable A thread can alter its cancellation at any time using the pthread setcanceltype function

Synchronization and Critical Sections There is no way to tell when a specific thread will be scheduled or at which line of code the OS will suspend one thread and re-schedule another If there is a concurrency bug, it is very hard to fix since it won t be deterministic The main cause of concurrency bugs is threads attempting to access the same resource/variable at the same time. This is called a race condition Race conditions can crash a program, or even worse leave variables in a corrupted state which could radically alter the behavior of the program

Race Condition #include <malloc.h> struct job struct job *next; }; struct job *job_queue; void* thread_function (void *arg) while (job_queue!= NULL) struct job *next_job = job_queue; job_queue = job_queue->next; process_job (next_job); } free (next_job); return NULL; }

Atomicity To avoid concurrency bugs and race conditions, you have to make sure that operations on shared variables are atomic An atomic operation means it is totally indivisible and uninterruptible To ensure atomicity we will use: Mutexes Semaphores

Atomicity (Cont.) Mutex stands for MUTual EXclusion locks A special lock that one thread can lock at a time, before enterting a critical section Any thread attempting to lock an already locked mutex will be blocked The underlying OS ensures that no race conditions will occur among threads using the mutex To create a mutex on Linux: pthread_mutex_t mutex; pthread_mutex_init (&mutex, NULL); To lock/unlock a mutex: pthread_mutex_lock (&mutex) pthread_mutex_unlock (&mutex)

process_job (next_job); free (next_job); } return NULL; } Mutex in action #include <malloc.h> #include <pthread.h>... pthread_mutex_t job_queue_mutex; pthread_mutex_init (&job_queue_mutex, NULL); void* thread_function (void *arg) while (1) struct job* next_job; /** Start of critical section **/ pthread_mutex_lock (&job_queue_mutex); if (job_queue == NULL) next_job = NULL; } else next_job = job_queue; job_queue = job_queue->next; } pthread_mutex_unlock (&job_queue_mutex); /** End of critical section **/

Deadlocks Mutexes introduce another type of concurrency bugs: deadlocks One or more threads can block forever waiting for a mutex to be unlocked A deadlock can easily take place if a thread who originally locked a mutex tries to lock it again In Linux, this can happen with the default type of mutexes, the fast mutex The recursive mutex, on the other hand, can be locked any number of times, but it must also be unlocked the same number of times

Semaphores In the previous queue example, what if all the jobs are not queued in advance? There is a possibility that threads can finish processing before all jobs are pushed onto the queue We need a semaphore to synchronize the threads, so that they can wait if there are no jobs on the queue at the moment

Semaphores (Cont.) A semaphore stores a non-negative counter which can be incremented/decremented. It supports two main operations: wait: decrements the value of a semaphore by one. If the value is already zero, the function blocks and hence the calling thread post: increments the value of a semaphore by one. If the value was originally zero, one of the blocked threads (if any) will be allowed to run We will use the POSIX standard semaphore for thread synchronization on Linux. There is another type of Linux semaphore used with processes (not covered) Semaphore common operations: sem_wait sem_post sem_trywait sem_getvalue // Non blocking wait // Get value of the semaphore

Semaphores Example #include <malloc.h> #include <pthread.h> #include <semaphore.h> struct job struct job *next; }; struct job *job_queue; pthread_mutex_t job_queue_mutex; pthread_mutex_init (&job_queue_mutex, NULL); sem_t job_queue_count; void initialize_job_queue () job_queue = NULL; sem_init (&job_queue_count, 0, 0); }...

Semaphores Example (cont.)... void* thread_function (void *arg) while (1) struct job *next_job; sem_wait (&job_queue_count); /** Start of critical section **/ pthread_mutex_lock (&job_queue_mutex); next_job = job_queue; job_queue = job_queue->next; pthread_mutex_unlock (&job_queue_mutex); /** End of critical section **/ process_job (next_job); free (next_job); } return NULL; }...

Semaphores Example (cont.)... void enqueue_job (/* Pass job-specific data here */) struct job *new_job; new_job = (struct job*) malloc (sizeof (struct job)); /** Start of critical section **/ pthread_mutex_lock (&job_queue_mutex); new_job->next = job_queue; job_queue = new_job; sem_post (&job_queue_count); pthread_mutex_unlock (&job_queue_mutex); /** End of critical section **/ }

Questions Questions?

References M. Mitchell, J. Oldham, and A. Samuel (2001). Threads, Advanced Linux Programming. Indianapolis:New Riders Publishing