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

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

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Multithreading Programming II

THREADS. Jo, Heeseung

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

ANSI/IEEE POSIX Standard Thread management

Chapter 4 Threads. Images from Silberschatz 03/12/18. CS460 Pacific University 1

Posix Threads (Pthreads)

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

Pthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Thread and Synchronization

Threads. Jo, Heeseung

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

Computer Systems Laboratory Sungkyunkwan University

POSIX Threads. Paolo Burgio

LSN 13 Linux Concurrency Mechanisms

POSIX Threads. HUJI Spring 2011

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

HPCSE - I. «Introduction to multithreading» Panos Hadjidoukas

CSE 333 SECTION 9. Threads

Threads. lightweight processes

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

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

Threads. Jo, Heeseung

real time operating systems course

Synchronization. Semaphores implementation

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

Synchronization Primitives

Introduc)on to pthreads. Shared memory Parallel Programming

pthreads CS449 Fall 2017

Process Synchronization

Chapter 4 Concurrent Programming

POSIX PTHREADS PROGRAMMING

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

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

Pthreads: POSIX Threads

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

Introduction to parallel computing

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

CS 3305 Intro to Threads. Lecture 6

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

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

CS Lecture 3! Threads! George Mason University! Spring 2010!

Parallel Programming with Threads

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

CSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks

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

Pthreads (2) Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.

Parallel Computing: Programming Shared Address Space Platforms (Pthread) Jin, Hai

Shared Memory Programming. Parallel Programming Overview

Introduction to PThreads and Basic Synchronization

Shared Memory: Virtual Shared Memory, Threads & OpenMP

Multithread Programming. Alexandre David

Introduction to Threads

Oct 2 and 4, 2006 Lecture 8: Threads, Contd

Shared Memory Programming Models III

More Shared Memory Programming

CS 470 Spring Mike Lam, Professor. Semaphores and Conditions

TCSS 422: OPERATING SYSTEMS

Lecture 19: Shared Memory & Synchronization

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

Paralleland Distributed Programming. Concurrency

CSCE 313: Introduction to Computer Systems

C Grundlagen - Threads

Concurrent Server Design Multiple- vs. Single-Thread

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

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

Computer Systems Laboratory Sungkyunkwan University

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

Concurrent Programming

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

Threads. studykorner.org

Chapter 5: Achieving Good Performance

Total Score is updated. The score of PA4 will be changed! Please check it. Will be changed

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

CSE 306/506 Operating Systems Threads. YoungMin Kwon

Programming Shared Address Space Platforms (cont.) Alexandre David B2-206

A Note About Makefiles. In OneFS/BSD be sure to build using gmake You may have to remove -pedantic-errors from CFLAGS

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

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

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

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

Operating systems and concurrency (B08)

PThreads in a Nutshell

Thread Concept. Thread. No. 3. Multiple single-threaded Process. One single-threaded Process. Process vs. Thread. One multi-threaded Process

CSE 333 Section 9 - pthreads

Concurrent Programming

CS 6400 Lecture 11 Name:

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

CMPSC 311- Introduction to Systems Programming Module: Concurrency

More Types of Synchronization 11/29/16

CS510 Operating System Foundations. Jonathan Walpole

dbug User Manual Computer Science Department Carnegie Mellon University

CMPSC 311- Introduction to Systems Programming Module: Concurrency

CS510 Operating System Foundations. Jonathan Walpole

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

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

CMPSC 311- Introduction to Systems Programming Module: Concurrency

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

Transcription:

COSC 6374 Parallel Computation Shared memory programming with POSIX Threads Fall 2012 References Some of the slides in this lecture is based on the following references: http://www.cobweb.ecn.purdue.edu/~eigenman/ece563/h andouts/pthreads.ppt W. Richard Stevens, Stephen A. Rago, Advanced Programming in the UNIX environment, Section 11, Addison- Wesley Professional Computing Series Rolf Rabenseifner, Georg Hager, Gabriele Jost, Rainer Keller, Hybrid MPI and OpenMP Parallel Programming, Tutorial S10 at Supercomputing 2007, Reno, Nevada, USA. http://www.yolinux.com/tutorials/linuxtutorialposixthre ads.html 1

POSIX Threads Overview Shared memory programming model POSIX threads (pthreads) programming model: creation of threads managing thread execution managing the shared resources of the process IEEE's POSIX Threads Model: programming models for threads in a UNIX platform pthreads are included in the international standards ISO/IEC9945-1 Execution model Main thread: initial thread created when main() (in C) are invoked by the process loader once in the main(), the application can create additional threads if the main thread returns, the process terminates even if there are running threads in that process, unless special precautions are taken (to explicitly avoid terminating the entire process, use pthread_exit() ) 2

Simple Example (I) #include <pthread.h> int main ( int argc, char **argv ) { int threadid, ret; // main thread spawns another thread ret = pthread_create (&threadid, NULL, tfunc, NULL); if ( ret!= 0 ) printf( Error creating a new thread\n ); } return (0); void *tfunc (void *arg){ pid_t pid; pthread_t tid; pid = getpid(); // determine the process id tid = pthread_self(); // determine the thread id return NULL; } pthread_create pthread_create ( pthread_t * tidp, const pthread_attr_t *attr void* (*start_rtn) func, void *arg); tidp: upon completion of the function set to the thread id of the new thread attr: argument used to customize the new thread func: function pointer to be executed by the new thread. The prototype of the function has to be void * func ( void *arg) arg: argument to be passed to the function func 3

pthread_self and getpid pid_t getpid(void); returns the process id of the calling process. all threads that have been spawned from a process have the same process id pthread_t pthread_self(void); returns the thread id of the calling thread not necessarily unique on a system, only within the calling process Thread termination If any thread within a process calls exit() the entire process is terminated. To terminate a thread without effecting the other threads return from the function. Return value is the exit code of the thread a thread can request that in the same process another thread is cancelled using int pthread_cancel(pthread_t *threadid); typically done by the main thread return 0 if ok, error number on failure. 4

A thread can call Thread termination (II) int pthread_exit(void *rval_ptr); rval_ptr: single argument to pass to the counter part can also be a pointer to a structure int pthread_join(pthread_t threadid, void **rval_ptr); typically called by the master thread rval_ptr: will contain the value passed by the terminating thread to pthread_exit() #include <pthread.h> Simple Example (II) int main ( int argc, char **argv ) { int threadid, ret; int *val; // main thread spawns another thread ret = pthread_create (&threadid, NULL, tfunc, NULL); if ( ret!= 0 ) printf( Error creating a new thread\n ); // do something pthread_join( threadid, &val); return (0); } void *tfunc (void *arg){ // do something useful pthread_exit ((void *) 1); return NULL; } 5

Thread synchronization Thread A Thread B read time write 1 write 2 read Reading and writing a shared variable between two threads Timing between two threads will differ in every iteration If you need a specific value for thread B of the variable you need to synchronize access to the shared variable Thread synchronization Three methods discussed here Mutex locks Condition variables Reader-Writer locks 6

Mutex locks Mutex: Mutual exclusion a lock is used before accessing a shared resource and released after the access mutex lock represented by a mutex variable while mutex lock is set, other threads that try to access the lock will be denied if more than one thread wait for the lock, all of them will be made runnable, but only one thread will get the lock All threads have to use mutex locks for accessing the variable, else no guarantee on correctness Mutex locks(ii) int pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t *attr); int pthread_mutex_destroy (pthread_mutex_t *mutex); mutex: mutex variable to be initialized/destroyed counter part once initialized, a mutex variable can be used for an unlimited number of lock/unlock operations attr: attributes for the mutex 7

Mutex locks (III) int pthread_mutex_lock (pthread_mutex_t *mutex ); int pthread_mutex_trylock (pthread_mutex_t *mutex ); int pthread_mutex_unlock (pthread_mutex_t *mutex ); pthread_mutex_lock: acquire lock for the mutex. If mutex is already blocked by another thread, wait until the mutex is unlocked pthread_mutex_trylock: acquire lock for the mutex. If mutex is already blocked by another thread, do not wait but return EBUSY to indicated failure Thread synchronization revisited Thread A Thread B read time write 1 write 2 read Example: Force thread B to read value of shared variable after write 2 8

Simple Example (IIIa) #include <pthread.h> int value=0; // shared variable pthread_mutex_t mymutex; // mutex variable int main ( int argc, char **argv ) { int threadid, ret; pthread_mutex_init (&mymutex,null); //Initialize mutex pthread_mutex_lock (&mymutex); // Acquire mutex lock // main thread spawns another thread ret = pthread_create (&threadid, NULL, tfunc, NULL); if ( ret!= 0 ) printf( Error creating a thread\n ); value = 1; // write 1 value ++; // write 2 pthread_mutex_unlock (&mymutex); // Release lock pthread_join( threadid, &val); // wait for other thread pthread_mutex_destroy (&mymutex); // destroy mutex return (0); Simple Example (IIIb) void *tfunc (void *arg){ int localvalue; pthread_mutex_lock (&mymutex); localvalue = value; pthread_mutex_unlock (&mymutex); // wait for lock // read shared variable } pthread_exit ((void *) 1); return NULL; 9

Mutex locks (IV) A thread will deadlock itself if it tries to lock the same mutex twice If more than one mutex is used a deadlock can occur if one thread holds lock 1 and waits for lock 2 and the other thread holds lock 2 and waits for lock 1 Order for accessing mutexes has to be identical in all code pathes e.g. need to hold lock 1 in order to be allowed to hold lock 2 Condition Variables The condition variable mechanism allows threads to suspend execution and relinquish the processor until some condition is true. must always be associated with a mutex int pthread_cond_init (pthread_cond_t *cond, pthread_condattr_t *attr ); int pthread_cond_destroy (pthread_cond_t *cond ); condition variable must be initialized before usage 10

Condition variables (II) int pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex ); Wait for a condition to be true Must be called with mutex locked by the calling thread will be released internally by the pthread_cond_wait() function all threads calling pthread_cond_wait() for the same condition variable will be added to a queue new thread acquiring the mutex lock can wake up the thread that called pthread_cond_wait() Condition Variables (III) int pthread_cond_signal (pthread_cond_t *cond ); int pthread_cond_broadcast (pthread_cond_t *cond); Wake up the next (pthread_cond_signal) or all (pthread_cond_broadcast) threads who are waiting on the condition only signal threads after changing the state of the condition 11

Task Parallelism using Master-Worker framework Master thread Worker thread 1 Worker thread 2 Result queue Task queue Master thread creates a work queue and assigns work for each thread Edgar threads Gabriel are sleeping until work is available #include <pthread.h> pthread_mutex_t mutex; // mutex variable pthread_cond_t cond; // condition variables work_struct work_item; // structure for work assignment int main ( int argc, char **argv ) { int threadids[num_threads], ret; pthread_mutex_init (&mutex,null); //Initialize mutex pthread_cond_init (&cond, NULL); //Initialize condition for ( int i=0; i<num_threads; i++ ) { ret = pthread_create (&threadids[i], NULL, fwake, NULL); if ( ret!= 0 ) printf( Error creating a thread\n ); } while (!done ){ // when next piece of work is available assign it to a // thread pthread_mutex_lock (&mutex ); work_assigned=yes; work_item = ; pthread_cond_signal (&cond); pthread_mutex_unlock(&mutex); } 12

void fwake (void *arg ) { work_t local_work; while (1) { pthread_mutex_lock(&mutex); if (work_assigned == NOTHING_YET) { //wait for work pthread_cond_wait(&cond, &mutex); } // Thread awake, perform work // e.g. remove the work from the work_queue // under protection of the lock if (work_assigned == DONE) clean_and_quit(); local_work=work_item; pthread_mutex_unlock(&mutex); // after work has been removed from queue, // release lock such that master can add // the next work piece and wake up another thread perform_work(local_work); } } Edgar } Gabriel Reader-Writer Lock Similar to mutexes but with three states locked in read mode locked in write mode unlocked Only one thread can hold a reader-writer lock in write mode if a write-mode lock is hold, all lock attempts (even read) are denied Multiple threads can hold a reader-writer in read mode Allows for higher level of parallelism 13

Reader-writer locks(ii) int pthread_rwlock_init (pthread_rwlock_t *rwlock, const pthread_rwlockattr_t *attr); int pthread_rwlock_destroy (pthread_rwlock_t *rwlock); int pthread_rwlock_rdlock (pthread_rwlock_t *rwlock); int pthread_rwlock_wrlock (pthread_rwlock_t *rwlock); int pthread_rwlock_unlock (pthread_rwlock_t *rwlock); Reentrant function Functions executed in a multi-threaded environment need to be re-rentrant it can be safely called again before its previous invocation has been completed Requirements: Must not hold static/global non-constant data. Must not return the address to global, non-constant data. Must work only on the data provided to it by the caller. Must not rely on locks to singleton resources. Must not call non-reentrant functions Note: some POSIX functions are not reentrant and have reentrant counterparts (e.g. strtok vs. strtok_r) 14