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

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

Roadmap. Concurrent Programming. Concurrent Programming. Motivation. Why Threads? Tevfik Ko!ar. CSC Systems Programming Fall 2010

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

Using make. Using Variables in Makefiles. Implicit Rules. Static vs Dynamic Libraries. Libraries. Tevfik Ko!ar

CSC Systems Programming Fall Lecture - XXIII Final Review. Tevfik Koşar. Louisiana State University

Exercise (could be a quiz) Solution. Concurrent Programming. Roadmap. Tevfik Koşar. CSE 421/521 - Operating Systems Fall Lecture - IV Threads

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

Introduction to PThreads and Basic Synchronization

Threads. Threads (continued)

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

CSE 333 SECTION 9. Threads

Threads. lightweight processes

POSIX PTHREADS PROGRAMMING

CMPSC 311- Introduction to Systems Programming Module: Concurrency

CMPSC 311- Introduction to Systems Programming Module: Concurrency

Summary of Last Class. Processes. C vs. Java. C vs. Java (cont.) C vs. Java (cont.) Tevfik Ko!ar. CSC Systems Programming Fall 2008

Parameter Passing in C. Pointer Arithmetic. Parameter Passing in C. Pointer Arithmetic. Pointer Arithmetic. Tevfik Ko!ar

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

CSC Systems Programming Fall Lecture - XV Network Programming - I. Tevfik Ko!ar. Louisiana State University. November 9 th, 2010

CMPSC 311- Introduction to Systems Programming Module: Concurrency

Threads. studykorner.org

Concurrent Server Design Multiple- vs. Single-Thread

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

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

Lecture 19: Shared Memory & Synchronization

Threads. Jo, Heeseung

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

CS 3305 Intro to Threads. Lecture 6

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

Multithreading. Reading: Silberschatz chapter 5 Additional Reading: Stallings chapter 4

LSN 13 Linux Concurrency Mechanisms

POSIX Threads. HUJI Spring 2011

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Basic C Program: Print to stdout. Basic C Program. Basic C Program: Print to stdout. Header Files. Read argument and print. Read argument and print

HPCSE - I. «Introduction to multithreading» Panos Hadjidoukas

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

Threads. Jo, Heeseung

pthreads CS449 Fall 2017

Environment Variables

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

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

The Fundamentals. Port Assignments. Common Protocols. Data Encapsulation. Protocol Communication. Tevfik Ko!ar

Concurrency and Synchronization. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

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

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

Operating systems fundamentals - B06

Chapter 4 Concurrent Programming

Thread and Synchronization

THREADS. Jo, Heeseung

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

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

Introduction to pthreads

Computer Systems Laboratory Sungkyunkwan University

High Performance Computing Course Notes Shared Memory Parallel Programming

Concurrency and Threads

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

Threads. Threads are an alternative to multiple processes. Different flows (or sequences) of execution operate on the same data (heap).

ANSI/IEEE POSIX Standard Thread management

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

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

Threads. What is a thread? Motivation. Single and Multithreaded Processes. Benefits

ENCM 501 Winter 2019 Assignment 9

Threaded Programming. Lecture 9: Alternatives to OpenMP

C Grundlagen - Threads

Concurrency. Johan Montelius KTH

User Space Multithreading. Computer Science, University of Warwick

POSIX Threads. Paolo Burgio

CSE 333 Section 9 - pthreads

CS333 Intro to Operating Systems. Jonathan Walpole

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

Overview. Administrative. * HW 2 Grades. * HW 3 Due. Topics: * What are Threads? * Motivating Example : Async. Read() * POSIX Threads

CPSC 341 OS & Networks. Threads. Dr. Yingwu Zhu

real time operating systems course

What is concurrency? Concurrency. What is parallelism? concurrency vs parallelism. Concurrency: (the illusion of) happening at the same time.

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

Parallel Programming with Threads

CS510 Operating System Foundations. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole

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

CSE 306/506 Operating Systems Threads. YoungMin Kwon

Multithreaded Programming

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

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

Motivation and definitions Processes Threads Synchronization constructs Speedup issues

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:

Introduction to Threads

Pthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

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

Pthread (9A) Pthread

Multicore and Multiprocessor Systems: Part I

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

Threads Tuesday, September 28, :37 AM

pthreads Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage)

Processes and Threads

Threads. CS-3013 Operating Systems Hugh C. Lauer. CS-3013, C-Term 2012 Threads 1

POSIX Threads: a first step toward parallel programming. George Bosilca

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

CSC209H Lecture 11. Dan Zingaro. March 25, 2015

Concurrent Programming

Multi-threaded Programming

Transcription:

CSC 4304 - Systems Programming Fall 2008 Lecture - XVIII Concurrent Programming Tevfik Ko!ar Louisiana State University November 11 th, 2008 1 Roadmap Concurrent Programming Shared Memory vs Message Passing Divide and Compute Threads vs Processes POSIX Threads 2

Concurrent Programming So far, we have focused on sequential programming: all computational tasks are executed in sequence, one after the other. Next three lectures, we will focus on concurrent programming: multiple computational tasks are executed simultaneously, at the same time. 1 2 3 2 1 4 3 5 concurrent 4 5 sequential 3 Concurrent Programming Implementation of concurrent tasks: as separate programs as a set of processes or threads created by a single program Execution of concurrent tasks: on a single processor! Multithreaded programming on several processors in close proximity! Parallel computing on several processors distributed across a network! Distributed computing 4

Communication Between Tasks Interaction or communication between concurrent tasks can done via: Shared memory: all tasks has access to the same physical memory they can communicate by altering the contents of shared memory Message passing: no common/shared physical memory tasks communicate by exchanging messages 5 Motivation Increase the performance by running more than one tasks at a time. divide the program to n smaller pieces, and run it n times faster using n processors To cope with independent physical devices. do not wait for a blocked device, perform other operations at the background 6

Serial vs Parallel COUNTER COUNTER 2 COUNTER 1 Q Please 7 Divide and Compute x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 How many operations with sequential programming? 7 Step 1: x1 + x2 Step 2: x1 + x2 + x3 Step 3: x1 + x2 + x3 + x4 Step 4: x1 + x2 + x3 + x4 + x5 Step 5: x1 + x2 + x3 + x4 + x5 + x6 Step 6: x1 + x2 + x3 + x4 + x5 + x6 + x7 Step 7: x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 8

Divide and Compute x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 Step 1: parallelism = 4 Step 2: parallelism = 2 Step 3: parallelism = 1 9 Gain from parallelism In theory: dividing a program into n smaller parts and running on n processors results in n time speedup In practice: This is not true, due to Communication costs Dependencies between different program parts Eg. the addition example can run only in log(n) time not 1/n 10

Prevent Blocking Do not wait for a blocked device, perform other operations at the background During I/O perform computation During continuous visualization, handle key strokes and I/O Eg. video games While listening to network, perform other operations Listening to multiple sockets at the same time Concurrent I/O, concurrent transfers Eg. Web browsers 11 Process Spawning: Threads vs Processes Process creation involves the following four main actions: setting up the process control block, allocation of an address space and loading the program into the allocated address space and passing on the process control block to the scheduler Thread Spawning: Threads are created within and belonging to processes All the threads created within one process share the resources of the process including the address space Scheduling is performed on a per-thread basis. The thread model is a finer grain scheduling model than the process model Threads have a similar lifecycle as the processes and will be managed mainly in the same way as processes are 12

Threads vs Processes Heavyweight Process = Process Lightweight Process = Thread Advantages (Thread vs. Process): Much quicker to create a thread than a process Much quicker to switch between threads than to switch between processes Threads share data easily Disadvantages (Thread vs. Process): Processes are more flexible They don t have to run on the same processor No security between threads: One thread can stomp on another thread's data For threads which are supported by user thread package instead of the kernel: If one thread blocks, all threads in task block. 13 Synchronization Mechanism that allows the programmer to control the relative order in which operations occur in different threads or processes. 14

Synchronization - Threads Int sum = 0; Thread 1: int t; lock(sum); sum = sum + x; t = sum;. unlock(sum); Thread 2: int t; lock(sum); sum = sum + y; t = sum; unlock(sum); Use of semaphores for thread synchronization! 15 Synchronization - Processes x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 Step 1: parallelism = 4 Step 2: parallelism = 2 Step 3: parallelism = 1 Wait for a message from other processes before continuing processing! 16

On a single processor machine You can have multiple threads You can also have multiple processes and have the effect of concurrency timesharing 17 Thread Creation pthread_create // creates a new thread executing start_routine int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg); pthread_join // suspends execution of the calling thread until the target // thread terminates int pthread_join(pthread_t thread, void **value_ptr); 18

Mutual Exclusion pthread_mutex_lock // blocks until mutex is available, and then locks it int pthread_mutex_lock(pthread_mutex_t *mutex); pthread_mutex_unlock // unlocks the mutex int pthread_mutex_unlock(pthread_mutex_t *mutex); 19 Thread Example int main() pthread_t thread1, thread2; /* thread variables */ pthread_create (&thread1, NULL, (void *) &print_message_function, (void*) hello ); pthread_create (&thread2, NULL, (void *) &print_message_function, (void*) world!\n ); pthread_join(thread1, NULL); pthread_join(thread2, NULL); exit(0); Why use pthread_join? To force main block to wait for both threads to terminate, before it exits. If main block exits, both threads exit, even if the threads have not finished their work. 20

Thread Example (cont.) void print_message_function ( void *ptr ) char *cp = (char*)ptr; for (i=0;i<num;i++) printf("%s ", cp); fflush(stdout); pthread_exit(0); /* exit */ 21 Interthread Cooperation void* print_count ( void *ptr ); void* increment_count ( void *ptr ); int NUM=5; int counter =0; int main() pthread_t thread1, thread2; pthread_create (&thread1, NULL, increment_count, NULL); pthread_create (&thread2, NULL, print_count, NULL); pthread_join(thread1, NULL); pthread_join(thread2, NULL); exit(0); 22

Interthread Cooperation (cont.) void* print_count ( void *ptr ) int i; for (i=0;i<num;i++) printf("counter = %d \n", counter); sleep(1); pthread_exit(0); void* increment_count ( void *ptr ) int i; for (i=0;i<num;i++) counter++; sleep(1); pthread_exit(0); 23 2-Thread Word Counter int total_words; main(int ac, char *av[]) pthread_t t1, t2; /* two threads */ void *count_words(void *); if ( ac!= 3 ) printf("usage: %s file1 file2\n", av[0]); exit(1); total_words = 0; pthread_create(&t1, NULL, count_words, (void *) av[1]); pthread_create(&t2, NULL, count_words, (void *) av[2]); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("%5d: total words\n", total_words); 24

2-Thread Word Counter (cont.) void *count_words(void *f) char *filename = (char *) f; FILE *fp; int c, prevc = '\0'; if ( (fp = fopen(filename, "r"))!= NULL ) while( ( c = getc(fp))!= EOF ) if (!isalnum(c) && isalnum(prevc) ) total_words++; prevc = c; fclose(fp); else perror(filename); return NULL; 25 2-Thread Word Counter, Mutex pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER; int total_words ; /* the counter and its lock */ main(int ac, char *av[])! pthread_t t1, t2;! /* two threads */! void! *count_words(void *);! if ( ac!= 3 )!! printf("usage: %s file1 file2\n", av[0]);!! exit(1);!! total_words = 0;! pthread_create(&t1, NULL, count_words, (void *) av[1]);! pthread_create(&t2, NULL, count_words, (void *) av[2]);! pthread_join(t1, NULL);! pthread_join(t2, NULL);! printf("%5d: total words\n", total_words); 26

2-Thread Word Counter, Mutex (cont.) void *count_words(void *f)! char *filename = (char *) f;! FILE *fp;! int c, prevc = '\0';!! if ( (fp = fopen(filename, "r"))!= NULL )!! while( ( c = getc(fp))!= EOF )!!! if (!isalnum(c) && isalnum(prevc) )!!!! pthread_mutex_lock(&counter_lock);!!!! total_words++;!!!! pthread_mutex_unlock(&counter_lock);!!!!!! prevc = c;!!!! fclose(fp);! else!! perror(filename);! return NULL; 27 2-Thread Word Counter, Arg Pass main(int ac, char *av[])! pthread_t t1, t2;!! /* two threads */! struct arg_set args1, args2;! /* two argsets */! void! *count_words(void *);! if ( ac!= 3 )!! printf("usage: %s file1 file2\n", av[0]);!! exit(1);!! args1.fname = av[1];! args1.count = 0;! pthread_create(&t1, NULL, count_words, (void *) &args1);! args2.fname = av[2];! args2.count = 0;! pthread_create(&t2, NULL, count_words, (void *) &args2);! pthread_join(t1, NULL);! pthread_join(t2, NULL);! printf("%5d: %s\n", args1.count, av[1]);! printf("%5d: %s\n", args2.count, av[2]);! printf("%5d: total words\n", args1.count+args2.count); 28

2-Thread Word Counter, Arg Pass (cont.) struct arg_set!! /* two values in one arg */!! char *fname;!/* file to examine! */!! int count;! /* number of words! */ ; void *count_words(void *a)! struct arg_set *args = a;!/* cast arg back to correct type */! FILE *fp;! int c, prevc = '\0';!! if ( (fp = fopen(args->fname, "r"))!= NULL )!! while( ( c = getc(fp))!= EOF )!!! if (!isalnum(c) && isalnum(prevc) )!!!! args->count++;!!! prevc = c;!!!! fclose(fp);! else!! perror(args->fname);! return NULL; 29 Acknowledgments Advanced Programming in the Unix Environment by R. Stevens The C Programming Language by B. Kernighan and D. Ritchie Understanding Unix/Linux Programming by B. Molay Lecture notes from B. Molay (Harvard), T. Kuo (UT- Austin), G. Pierre (Vrije), M. Matthews (SC), B. Knicki (WPI), M. Shacklette (UChicago), J.Kim (KAIST), and J. Schaumann (SIT). 30