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

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

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

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

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

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

Lecture 19: Shared Memory & Synchronization

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

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

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

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

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Threads. Jo, Heeseung

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

POSIX Threads. HUJI Spring 2011

CS 3305 Intro to Threads. Lecture 6

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

pthreads CS449 Fall 2017

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

Threads. Jo, Heeseung

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

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

Environment Variables

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

Operating systems fundamentals - B06

Thread and Synchronization

THREADS. Jo, Heeseung

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

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

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

Chapter 4 Concurrent Programming

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

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

ENCM 501 Winter 2019 Assignment 9

C Grundlagen - Threads

Concurrency. Johan Montelius KTH

User Space Multithreading. Computer Science, University of Warwick

POSIX Threads. Paolo Burgio

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

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

real time operating systems course

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

Parallel Programming with Threads

Threaded Programming. Lecture 9: Alternatives to OpenMP

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

CS510 Operating System Foundations. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole

CSE 306/506 Operating Systems Threads. YoungMin Kwon

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

CSE 333 Section 9 - pthreads

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

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

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

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

Pthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Pthread (9A) Pthread

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

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

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

Threads Tuesday, September 28, :37 AM

Processes and Threads

Multithreaded Programming

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

CSC209H Lecture 11. Dan Zingaro. March 25, 2015

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

Concurrent Programming

Multicore and Multiprocessor Systems: Part I

Network Programming TDC 561

Posix Threads (Pthreads)

TCSS 422: OPERATING SYSTEMS

Transcription:

CSC 0 - Systems Programming Fall 008 Lecture - XVIII Roadmap Shared Memory vs Message Passing Divide and Compute Threads vs Processes POSIX Threads Tevfik Ko!ar Louisiana State University November th, 008 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. concurrent 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 sequential Communication Between Tasks Motivation 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 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 Divide and Compute COUNTER COUNTER x + x + x + x + x + x6 + x7 + x8 COUNTER How many operations with sequential programming? 7 Q Please Step : x + x Step : x + x + x Step : x + x + x + x Step : x + x + x + x + x Step : x + x + x + x + x + x6 Step 6: x + x + x + x + x + x6 + x7 Step 7: x + x + x + x + x + x6 + x7 + x8 7 8 Divide and Compute x + x + x + x + x + x6 + x7 + x8 Step : parallelism = Gain from parallelism In theory: dividing a program into n smaller parts and running on n processors results in n time speedup Step : parallelism = Step : parallelism = 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 /n 9 0 Prevent Blocking Threads vs Processes 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 Process Spawning: 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

Threads vs Processes Synchronization 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 Mechanism that allows the programmer to control the relative order in which operations occur in different threads or processes. 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. Synchronization - Threads Synchronization - Processes Int sum = 0; x + x + x + x + x + x6 + x7 + x8 Thread : int t; lock(sum); sum = sum + x; t = sum;. unlock(sum); Thread : int t; lock(sum); sum = sum + y; t = sum; unlock(sum); Step : parallelism = Step : parallelism = Step : parallelism = Use of semaphores for thread synchronization! Wait for a message from other processes before continuing processing! 6 On a single processor machine Thread Creation You can have multiple threads You can also have multiple processes and have the effect of concurrency timesharing 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); 7 8

Mutual Exclusion pthread_mutex_lock // blocks until mutex is available, and then locks it int pthread_mutex_lock(pthread_mutex_t *mutex); Thread Example int main() pthread_t thread, thread; /* thread variables */ pthread_create (&thread, NULL, (void *) &print_message_function, (void*) hello ); pthread_create (&thread, NULL, (void *) &print_message_function, (void*) world!\n ); pthread_mutex_unlock // unlocks the mutex int pthread_mutex_unlock(pthread_mutex_t *mutex); pthread_join(thread, NULL); pthread_join(thread, 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. 9 0 Thread Example (cont.) void print_message_function ( void *ptr ) char *cp = (char*)ptr; void* print_count ( void *ptr ); void* increment_count ( void *ptr ); Interthread Cooperation for (i=0;i<num;i++) printf("%s ", cp); fflush(stdout); pthread_exit(0); /* exit */ int NUM=; int counter =0; int main() pthread_t thread, thread; pthread_create (&thread, NULL, increment_count, NULL); pthread_create (&thread, NULL, print_count, NULL); pthread_join(thread, NULL); pthread_join(thread, NULL); exit(0); Interthread Cooperation (cont.) -Thread Word Counter void* print_count ( void *ptr ) int total_words; int i; for (i=0;i<num;i++) printf("counter = %d \n", counter); sleep(); pthread_exit(0); void* increment_count ( void *ptr ) int i; for (i=0;i<num;i++) counter++; sleep(); pthread_exit(0); pthread_t t, t; /* two threads */ void *count_words(void *); if ( ac!= ) printf("usage: %s file file\n", av[0]); exit(); total_words = 0; pthread_create(&t, NULL, count_words, (void *) av[]); pthread_create(&t, NULL, count_words, (void *) av[]); pthread_join(t, NULL); pthread_join(t, NULL); printf("%d: total words\n", total_words);

-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; -Thread Word Counter, Mutex pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER; int total_words ; /* the counter and its lock */! pthread_t t, t;! /* two threads */! void! *count_words(void *);! if ( ac!= )!! printf("usage: %s file file\n", av[0]);!! exit();!! total_words = 0;! pthread_create(&t, NULL, count_words, (void *) av[]);! pthread_create(&t, NULL, count_words, (void *) av[]);! pthread_join(t, NULL);! pthread_join(t, NULL);! printf("%d: total words\n", total_words); 6 -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); -Thread Word Counter, Arg Pass! pthread_t t, t;!! /* two threads */! struct arg_set args, args;! /* two argsets */! void! *count_words(void *);! if ( ac!= )!! printf("usage: %s file file\n", av[0]);!! exit();!! args.fname = av[];! args.count = 0;! pthread_create(&t, NULL, count_words, (void *) &args);!!!!!! prevc = c;!!!! fclose(fp);! else!! perror(filename);! return NULL; 7! args.fname = av[];! args.count = 0;! pthread_create(&t, NULL, count_words, (void *) &args);! pthread_join(t, NULL);! pthread_join(t, NULL);! printf("%d: %s\n", args.count, av[]);! printf("%d: %s\n", args.count, av[]);! printf("%d: total words\n", args.count+args.count); 8 -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; 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). 9 0