Posix Threads (Pthreads)

Size: px
Start display at page:

Download "Posix Threads (Pthreads)"

Transcription

1 Posix Threads (Pthreads) Reference: Programming with POSIX Threads by David R. Butenhof, Addison Wesley, 1997

2 Threads: Introduction main: startthread( funk1 ) startthread( funk1 ) startthread( funk2 ) wait exit main wait exit funk1 funk1 funk2 exit exit exit

3 Threads: Advantages Intuitive Modeling True parallelization Server Wait for connection Launch thread Client 1 Client 2 Client 3 Client processing... Client processing... Client processing

4 Threads: Synchronization Race conditions: Object to process Processing Thread Assembly Thread 1. Object not ready for processing 4. Wait for signal 2. Place object 3. Signal object ready for processing

5 Threads: Synchronization Deadlocks: Thread 1 Thread 2 1. Seize object A 3. Seize object B... Release object A Release object B 2. Seize object B 4. Seize object A... Release object B Release object A

6 Threads: Reentrancy Thread 1 process( /etc/data/results.txt ) Thread 2 process( /tmp/data.txt ) process( param ) 1. token = strtok( param ) 6. while ( token!= NULL ) token = strtok( NULL ) process( param ) 2. token = strtok( param ) 3. while ( token!= NULL ) token = strtok( NULL )

7 Pthreads: pthread_create typedef void *START_PROC_t( void * ); typedef START_PROC_t *START_PROC_p_t; int pthread_create( pthread_t *thread, const pthread_attr_t *attr, START_PROC_p_t start_proc, void *arg ); thread pointer to thread ID storage attr pointer to thread attributes object; may be NULL thread pointer to work function arg argument to pass to work function returns: 0 for success, non 0 for error

8 Pthreads: pthread_create Example static START_PROC_t funk1; int main( int argc, char **argv ) { pthread_t tid1; int arg1 = 1; status = pthread_create( &tid1, NULL, funk1, &arg1 ); if ( status!= 0 )... return 0; }

9 Pthreads: pthread_join int pthread_join(pthread_t thread, void **retval); Waits for a thread to terminate; returns immediately if thread has already terminated. thread ID of thread to join retval pointer to storage for joined thread s return value; may be NULL returns: 0 for success, non 0 for error

10 Pthreads: pthread_join, Example int main( int argc, char **argv ) { pthread_t tid1; int arg1 = 1; status = pthread_create( &tid1, NULL, funk1, &arg1 ); if ( status!= 0 )... status = pthread_join( tid1, NULL ); if ( status!= 0 )... return 0; }

11 Pthreads: pthread_cancel int pthread_cancel(pthread_t thread); Gracefully terminates a thread. thread The thread to terminate. Returns: 0 if successful, non zero otherwise.

12 Pthreads: pthread_cancel, Example int main( int argc, char **argv ) { pthread_t tid1; int arg1 = 1; status = pthread_create( &tid1, NULL, funk1, &arg1 ); if ( status!= 0 )... sleep( 60 ); status = pthread_cancel( tid1 ); if ( status!= 0 )... return 0; }

13 pth_util.h /************** BEGIN SPECIAL CONDITION: STATUS ******************** * To use any of the following macros you must first define variable * 'int status.' This is less than ideal, but we'll go with it for * now. */ #define PTH_CREATE( p1, p2, p3, p4 ) \ ((status = pthread_create( (p1), (p2), (p3), (p4) )) == 0? (void)0 : \ PTH_err( status, "pthread_create", FILE, LINE ) \ ) #define PTH_CANCEL( p1 ) \ ((status = pthread_cancel( (p1) )) == 0? (void)0 : \ PTH_err( status, "pthread_cancel", FILE, LINE ) \ )... /************** END SPECIAL CONDITION: STATUS ********************/

14 pth_util.c void PTH_err( int status, const char *msg, const char *file, int line ) { const char *status_str = strerror( status ); fprintf( stderr, "Error %d (%s); %s in %s at line %d\n", status, status_str, msg, file, line ); abort(); }

15 Exercise 1. From the class website download pth_utils.h, pth_utils.c and thread_exercise1.c. 2. Complete the code in thread_exercise1.c. This will create three threads that separately add the numbers between 1 and 1,000,000; 1,000,0001 and 2,000,000; and 2,000,001 and 3,000,000,000 then combine the results. 3. Add PTH_EXIT (which invokes pthread_exit) to pth_utils.h.

16 Threads: Mutexes A mutex is an object that is used for thread synchronization. mutex_a Thread 1 process( /etc/data/results.txt ) Thread 2 process( /tmp/data.txt ) process( param ) 1. sieze mutex_a 3. token = strtok( param ) 4. while ( token!= NULL ) token = strtok( NULL ) 7. release mutex_a process( param ) 2. sieze mutex_a (wait) 8. token = strtok( param ) 9. while ( token!= NULL ) token = strtok( NULL ) 12. release mutex_a

17 Pthreads: pthread_mutex_init int pthread_mutex_init( pthread_mutex_t *mutex, const pthread_mutexattr_t *attr ); mutex Pointer to storage for a mutex identifier. attr Pointer to a mutex attributes object; may be NULL. returns: 0 if successful, non zero otherwise

18 Pthreads: PTHREAD_MUTEX_INITIALIZER This macro may be used to initialize static mutexes: static pthread_mutex_t mutex_ = PTHREAD_MUTEX_INITIALIZER; No error checking is performed.

19 Pthreads: pthread_mutex_destroy int pthread_mutex_destroy( pthread_mutex_t *mutex ); mutex Pointer to storage for a mutex identifier. returns: 0 if successful, non zero otherwise Do not try to destroy an uninitialized mutex. Do not try to destroy a locked mutex. Once a mutex has been destroyed it may be reinitialized.

20 Pthreads: Mutex Locking/Unlocking int pthread_mutex_lock( pthread_mutex_t *mutex ); Sieze a mutex; if the mutex is already locked wait until it is unlocked. int pthread_mutex_trylock( pthread_mutex_t *mutex ); Sieze a mutex; if the mutex is already locked return immediately with a status of EBUSY. int pthread_mutex_unlock( pthread_mutex_t *mutex ); Release a mutex; do not try to release an unlocked mutex. Return: 0 if success, non zero otherwise.

21 Pthreads: pthread_mutexattr_t int pthread_mutexattr_init(pthread_mutexattr_t *attr); Initialize a Pthread mutex attrbutes object. int pthread_mutexattr_destroy(pthread_mutexattr_t *attr); Destroy a Pthread mutex attrbutes object. int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type); Set the type of a Pthread mutex object. attr Pointer to Pthread mutex attributes object storage. type Type of a Pthread mutex object.

22 Pthreads: Mutex Type PTHREAD_MUTEX_NORMAL Recursive acquistion of a mutex will result in a deadlock. Attempting to unlock a mutex owned by another thread will result in undefined behavior. PTHREAD_MUTEX_ERRORCHECK Attempted recursive acquistion of a mutex will return a status of EDEADLK. Attempting to unlock a mutex owned by another thread will return a status of EPERM. PTHREAD_MUTEX_RECURSIVE Recursive acquistion of a mutex is allowed. Attempting to unlock a mutex owned by another thread will return a status of EPERM. PTHREAD_MUTEX_DEFAULT Recursive acquistion of a mutex will result in undefined behavior. Attempting to unlock a mutex owned by another thread will result in undefined behavior. This functionality may not be available on all systems; check your documentation.

23 Pthreads: Mutex Type, Example static void init_mutex( void ) { pthread_mutexattr_t attrs; int status; } status = pthread_mutexattr_init( &attrs ); if ( status!= 0 ) err( status, "pthread_mutexattr_init" ); status = pthread_mutexattr_settype( &attrs, PTHREAD_MUTEX_ERRORCHECK ); if ( status!= 0 ) err( status, "pthread_mutexattr_settype" ); status = pthread_mutex_init( &mutex_var_, &attrs ); if ( status!= 0 ) err( status, "pthread_mutex_init" ); status = pthread_mutexattr_destroy( &attrs ); if ( status!= 0 ) err( status, "pthread_mutexattr_destroy" );

24 Pthreads: Mutex Type, Example (cont d) static void cleanup( void ) { int status = pthread_mutex_destroy( &mutex_var_ ); if ( status!= 0 ) err( status, "pthread_mutex_destroy" ); }

25 Exercise 1. Write and test the function int get_random_int( int min, int max ). This function uses the function rand() (declared in stdlib.h) to generate and return a random integer between min and max, inclusive. The algorithm for doing this is given by: rand() % (max min + 1) + min 2. Write a program, mutex_exercise, with a counter and two threads: One thread increments the counter up to a maximum value of 5, reports the counter value (via printf()) and sleeps for a random number of seconds no less than 2 and no more than 5. The other thread decrements the counter to a minimum value of 0, reports the counter value and sleeps for a random number of seconds no less than 1 and no more than 4. Use a mutex to ensure that the two threads do not try to adjust the counter or report its value at the same time.

26 Threads: Sometimes a Mutex is Not Enough Object to process Processing Thread 1. Seize mutex 2. Object not ready for processing 3. Release mutex 8. Wait for signal mutex_a Assembly Thread 4. Seize mutex 5. Place object 6. Signal object ready for processing 7. Release mutex

27 Pthreads: Condition Variables Condition variables allow you to release a mutex and initiate a wait as an atomic process. Object to process Processing Thread 1. Seize mutex 2. Object not ready for processing 3. Wait on condition via mutex mutex_a cond_a Assembly Thread 4. Seize mutex 5. Place object 6. Signal object ready for processing 7. Release mutex

28 Pthreads: pthread_cond_init int pthread_mutex_init( pthread_cond_t *cond, const pthread_condattr_t *attr ); cond Pointer to storage for a condition variable identifier. attr Pointer to a condition variable attributes object; may be NULL. returns: 0 if successful, non zero otherwise

29 Pthreads: PTHREAD_COND_INITIALIZER This macro may be used to initialize static condition variables: static pthread_cond_t cond_ = PTHREAD_COND_INITIALIZER; No error checking is performed.

30 Pthreads: pthread_cond_destroy int pthread_cond_destroy( pthread_cond_t *cond ); cond Pointer to storage for a condition variable identifier. Returns: 0 if successful, non zero otherwise Do not try to destroy an uninitialized condition variable. Do nottry to destroy a blocking condition variable. Once a condition variable has been destroyed it may be reinitialized.

31 Pthreads: Using Condition Variables int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); Release mutex, block on cond. int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime); Release mutex, block on cond for at most abstime. int pthread_cond_signal(pthread_cond_t *cond); Unblock at least one thread waiting on cond. int pthread_cond_broadcast(pthread_cond_t *cond); Unblock all threads waiting on cond.! A condition variable always wakes with its mutex locked. Return: 0 on success, non 0 otherwise. pthread_cond_timedwait returns ETIMEDOUT in the case of a time out.

32 Pthreads: Condition Variable Example Baker Thread bake_pie(); while ( 1 ) { bool bake_another = false; PTH_MUTEX_LOCK( &mutex_ ); if ( num_pies_ < max_pies_ ) { ++num_pies_; bake_another = true; PTH_COND_SIGNAL( &driver_cond_ ); } else PTH_COND_WAIT( &baker_cond_, &mutex_ ); PTH_MUTEX_UNLOCK( &mutex_ ); if ( bake_another ) bake_pie(); } 1. Bake a pie. 2. Lock If there s room in the queue: a) Add the pie to the queue. b) Signal the driver. 4. If there s no room in the queue: a) wait 5. Unlock If possible, bake another pie.

33 Pthreads: Condition Variable Example (cont.) Driver Thread while ( 1 ) { bool deliver = false; PTH_MUTEX_LOCK( &mutex_ ); if ( num_pies_ > 0 ) { --num_pies_; deliver = true; PTH_COND_SIGNAL( &baker_cond_ ); } else PTH_COND_WAIT( &driver_cond_, &mutex_ ); PTH_MUTEX_UNLOCK( &mutex_ ); if ( deliver ) deliver_pie(); } 1. Lock If a pie is in the queue: a) Remove it from the queue. b) Signal the baker. 3. If no pie is waiting a) Wait 4. Unlock If necessary, deliver the pie

34 Exercises 1. Add the macro PTH_COND_TIMEDWAIT (which invokes pthread_cond_timedwait) to pth_utils.h. 2. Modify mutex_exercise so that: It contains a condition variabe When the incrementing thread successfully increments the counter it signals the condition variable; if it can t increment the counter it waits on the condition variable. When the decrementing thread successfully decrements the counter it signals the condition variable; if it can t decrement the counter it waits on the condition variable.

35 Pthreads: pthread_once typedef void ONCE_PROC_t( void ); typedef ONCE_PROC_t *ONCE_PROC_p_t; int pthread_once( pthread_once_t *control, ONCE_PROC_p_t init_proc ); For performing global initialization once. control Variable to control initialization; MUST be statically allocated, MUST be initialized with PTHREAD_ONCE_INIT. init_proc Address of initialization function. Returns: 0 for success, non zero otherwise.

36 Pthreads: pthread_once, Example int main( int argc, char **argv ) { int status; PTH_CREATE( &thr1_, NULL, thr_start, NULL ); PTH_CREATE( &thr2_, NULL, thr_start, NULL ); PTH_CREATE( &thr3_, NULL, thr_start, NULL );... } static void init( void ) { puts( "init starting" ); // perform global initialization here puts( "init ending" ); } static void *thr_start( void *arg ) { static pthread_once_t init_once = PTHREAD_ONCE_INIT; int status; PTH_ONCE( &init_once, init );... } Output: init starting init ending

37 Pthreads: Mutex Attributes See: pthread_mutexattr_setpshared; PTHREAD_PROCESS_SHARED: allow mutexes to control threads in multiple processes. PTHREAD_PROCESS_PRIVATE: mutexes may not be accessed outside the initializing process. See: pthread_mutexattr_setprioceiling; Sets the maximum priority for the critical section guarded by a mutex. See: pthread_mutexattr_setprotocol; Controls the priority and scheduling of threads that own the target mutex. Systems are not required to implement this functionality; check your documentation.

38 Pthreads: Condition Variable Attributes See: pthread_condattr_setpshared; PTHREAD_PROCESS_SHARED: allow a condition variable to control threads in multiple processes. PTHREAD_PROCESS_PRIVATE: condition variables may not be accessed outside the initializing process. Systems are not required to implement this functionality; check your documentation.

39 Pthreads: Thread Attributes See: pthread_attr_setdetachstate pthread_attr_setguardsize pthread_attr_setinheritsched pthread_attr_setschedparam pthread_attr_setschedpolicy pthread_attr_setscope pthread_attr_setstackaddr pthread_attr_setstacksize Systems are not required to implement all of this functionality; check your documentation.

real time operating systems course

real time operating systems course real time operating systems course 4 introduction to POSIX pthread programming introduction thread creation, join, end thread scheduling thread cancellation semaphores thread mutexes and condition variables

More information

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

COSC 6374 Parallel Computation. Shared memory programming with POSIX Threads. Edgar Gabriel. Fall References 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

More information

ANSI/IEEE POSIX Standard Thread management

ANSI/IEEE POSIX Standard Thread management Pthread Prof. Jinkyu Jeong( jinkyu@skku.edu) TA Jinhong Kim( jinhong.kim@csl.skku.edu) TA Seokha Shin(seokha.shin@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu The

More information

POSIX Threads. Paolo Burgio

POSIX Threads. Paolo Burgio POSIX Threads Paolo Burgio paolo.burgio@unimore.it The POSIX IEEE standard Specifies an operating system interface similar to most UNIX systems It extends the C language with primitives that allows the

More information

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

Threads need to synchronize their activities to effectively interact. This includes: KING FAHD UNIVERSITY OF PETROLEUM AND MINERALS Information and Computer Science Department ICS 431 Operating Systems Lab # 8 Threads Synchronization ( Mutex & Condition Variables ) Objective: When multiple

More information

POSIX PTHREADS PROGRAMMING

POSIX PTHREADS PROGRAMMING POSIX PTHREADS PROGRAMMING Download the exercise code at http://www-micrel.deis.unibo.it/~capotondi/pthreads.zip Alessandro Capotondi alessandro.capotondi(@)unibo.it Hardware Software Design of Embedded

More information

Threads. Jo, Heeseung

Threads. Jo, Heeseung Threads Jo, Heeseung Multi-threaded program 빠른실행 프로세스를새로생성에드는비용을절약 데이터공유 파일, Heap, Static, Code 의많은부분을공유 CPU 를보다효율적으로활용 코어가여러개일경우코어에 thread 를할당하는방식 2 Multi-threaded program Pros. Cons. 대량의데이터처리에적합 - CPU

More information

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

Synchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1 Synchronization and Semaphores Copyright : University of Illinois CS 241 Staff 1 Synchronization Primatives Counting Semaphores Permit a limited number of threads to execute a section of the code Binary

More information

Multithreading Programming II

Multithreading Programming II Multithreading Programming II Content Review Multithreading programming Race conditions Semaphores Thread safety Deadlock Review: Resource Sharing Access to shared resources need to be controlled to ensure

More information

Pthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Pthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University Pthreads Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu The Pthreads API ANSI/IEEE POSIX1003.1-1995 Standard Thread management Work directly on

More information

Threads. Jo, Heeseung

Threads. Jo, Heeseung Threads Jo, Heeseung Multi-threaded program 빠른실행 프로세스를새로생성에드는비용을절약 데이터공유 파일, Heap, Static, Code 의많은부분을공유 CPU 를보다효율적으로활용 코어가여러개일경우코어에 thread 를할당하는방식 2 Multi-threaded program Pros. Cons. 대량의데이터처리에적합 - CPU

More information

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

Synchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1 Synchronization and Semaphores Copyright : University of Illinois CS 241 Staff 1 Synchronization Primatives Counting Semaphores Permit a limited number of threads to execute a section of the code Binary

More information

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

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto For more information please consult Advanced Programming in the UNIX Environment, 3rd Edition, W. Richard Stevens and

More information

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

A Note About Makefiles. In OneFS/BSD be sure to build using gmake You may have to remove -pedantic-errors from CFLAGS PThreads A Note About Makefiles In OneFS/BSD be sure to build using gmake You may have to remove -pedantic-errors from CFLAGS Creating/Starting a Thread (1 of 4) #include typedef void *THREAD_PROC_t(

More information

Thread and Synchronization

Thread and Synchronization Thread and Synchronization pthread Programming (Module 19) Yann-Hang Lee Arizona State University yhlee@asu.edu (480) 727-7507 Summer 2014 Real-time Systems Lab, Computer Science and Engineering, ASU Pthread

More information

LSN 13 Linux Concurrency Mechanisms

LSN 13 Linux Concurrency Mechanisms LSN 13 Linux Concurrency Mechanisms ECT362 Operating Systems Department of Engineering Technology LSN 13 Creating Processes fork() system call Returns PID of the child process created The new process is

More information

Synchronization Primitives

Synchronization Primitives Synchronization Primitives Locks Synchronization Mechanisms Very primitive constructs with minimal semantics Semaphores A generalization of locks Easy to understand, hard to program with Condition Variables

More information

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

Lecture 4. Threads vs. Processes. fork() Threads. Pthreads. Threads in C. Thread Programming January 21, 2005 Threads vs. Processes Lecture 4 Thread Programming January 21, 2005 fork() is expensive (time, memory) Interprocess communication is hard. Threads are lightweight processes: one process can contain several

More information

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University Threads Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu) Concurrency

More information

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

CS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization CS-345 Operating Systems Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization Threads A thread is a lightweight process A thread exists within a process and uses the process resources. It

More information

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

Agenda. Process vs Thread. ! POSIX Threads Programming. Picture source: Agenda POSIX Threads Programming 1 Process vs Thread process thread Picture source: https://computing.llnl.gov/tutorials/pthreads/ 2 Shared Memory Model Picture source: https://computing.llnl.gov/tutorials/pthreads/

More information

POSIX Threads. HUJI Spring 2011

POSIX Threads. HUJI Spring 2011 POSIX Threads HUJI Spring 2011 Why Threads The primary motivation for using threads is to realize potential program performance gains and structuring. Overlapping CPU work with I/O. Priority/real-time

More information

Threads. lightweight processes

Threads. lightweight processes Threads lightweight processes 1 Motivation Processes are expensive to create. It takes quite a bit of time to switch between processes Communication between processes must be done through an external kernel

More information

Synchronization Mechanisms

Synchronization Mechanisms Synchronization Mechanisms CSCI 4061 Introduction to Operating Systems Instructor: Abhishek Chandra Mutex Locks Enforce protection and mutual exclusion Condition variables Allow atomic checking of conditions

More information

Introduction to parallel computing

Introduction to parallel computing Introduction to parallel computing Shared Memory Programming with Pthreads (3) Zhiao Shi (modifications by Will French) Advanced Computing Center for Education & Research Vanderbilt University Last time

More information

THREADS. Jo, Heeseung

THREADS. Jo, Heeseung THREADS Jo, Heeseung TODAY'S TOPICS Why threads? Threading issues 2 PROCESSES Heavy-weight A process includes many things: - An address space (all the code and data pages) - OS resources (e.g., open files)

More information

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

Pthreads (2) Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University   Embedded Software Lab. 1 Pthreads (2) Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University http://nyx.skku.ac.kr Last Class Review 2 ANSI/IEEE POSIX1003.1-95 Standard Thread management Work directly on threads

More information

Process Synchronization

Process Synchronization Process Synchronization Part III, Modified by M.Rebaudengo - 2013 Silberschatz, Galvin and Gagne 2009 POSIX Synchronization POSIX.1b standard was adopted in 1993 Pthreads API is OS-independent It provides:

More information

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

Chapter 4 Threads. Images from Silberschatz 03/12/18. CS460 Pacific University 1 Chapter 4 Threads Images from Silberschatz Pacific University 1 Threads Multiple lines of control inside one process What is shared? How many PCBs? Pacific University 2 Typical Usages Word Processor Web

More information

CSE 333 SECTION 9. Threads

CSE 333 SECTION 9. Threads CSE 333 SECTION 9 Threads HW4 How s HW4 going? Any Questions? Threads Sequential execution of a program. Contained within a process. Multiple threads can exist within the same process. Every process starts

More information

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

Parallel Computing: Programming Shared Address Space Platforms (Pthread) Jin, Hai Parallel Computing: Programming Shared Address Space Platforms (Pthread) Jin, Hai School of Computer Science and Technology Huazhong University of Science and Technology Thread Basics! All memory in the

More information

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

pthreads Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage) pthreads 1 Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage) 2 1 Thread Packages Kernel thread packages Implemented and supported at kernel

More information

Paralleland Distributed Programming. Concurrency

Paralleland Distributed Programming. Concurrency Paralleland Distributed Programming Concurrency Concurrency problems race condition synchronization hardware (eg matrix PCs) software (barrier, critical section, atomic operations) mutual exclusion critical

More information

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

Pre-lab #2 tutorial. ECE 254 Operating Systems and Systems Programming. May 24, 2012 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

More information

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

Preview. What are Pthreads? The Thread ID. The Thread ID. The thread Creation. The thread Creation 10/25/2017 Preview What are Pthreads? What is Pthreads The Thread ID The Thread Creation The thread Termination The pthread_join() function Mutex The pthread_cancel function The pthread_cleanup_push() function The

More information

Computer Systems Laboratory Sungkyunkwan University

Computer Systems Laboratory Sungkyunkwan University Threads Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Today s Topics Why threads? Threading issues 2 Processes Heavy-weight A process includes

More information

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

CMPS 105 Systems Programming. Prof. Darrell Long E2.371 + CMPS 105 Systems Programming Prof. Darrell Long E2.371 darrell@ucsc.edu + Chapter 12: Thread Control + Thread Limits: Portability + Thread Attributes n Thread attributes control the behavior of threads

More information

CSE 333 Section 9 - pthreads

CSE 333 Section 9 - pthreads CSE 333 Section 9 - pthreads Welcome back to section! We re glad that you re here :) Process A process has a virtual address space. Each process is started with a single thread, but can create additional

More information

Chapter 5: Achieving Good Performance

Chapter 5: Achieving Good Performance Chapter 5: Achieving Good Performance Typically, it is fairly straightforward to reason about the performance of sequential computations. For most programs, it suffices simply to count the number of instructions

More information

Chapter 4 Concurrent Programming

Chapter 4 Concurrent Programming Chapter 4 Concurrent Programming 4.1. Introduction to Parallel Computing In the early days, most computers have only one processing element, known as the Central Processing Unit (CPU). Due to this hardware

More information

C Grundlagen - Threads

C Grundlagen - Threads Michael Strassberger saremox@linux.com Proseminar C Grundlagen Fachbereich Informatik Fakultaet fuer Mathematik, Informatik und Naturwissenschaften Universitaet Hamburg 3. Juli 2014 Table of Contents 1

More information

CSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks

CSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks CSci 4061 Introduction to Operating Systems Synchronization Basics: Locks Synchronization Outline Basics Locks Condition Variables Semaphores Basics Race condition: threads + shared data Outcome (data

More information

Introduc)on to pthreads. Shared memory Parallel Programming

Introduc)on to pthreads. Shared memory Parallel Programming Introduc)on to pthreads Shared memory Parallel Programming pthreads Hello world Compute pi pthread func)ons Prac)ce Problem (OpenMP to pthreads) Sum and array Thread-safe Bounded FIFO Queue pthread Hello

More information

Real Time Operating Systems and Middleware

Real Time Operating Systems and Middleware Real Time Operating Systems and Middleware POSIX Threads Synchronization Luca Abeni abeni@dit.unitn.it Real Time Operating Systems and Middleware p. 1 Threads Synchronisation All the threads running in

More information

Concurrency, Parallel and Distributed

Concurrency, Parallel and Distributed Threads (Chapter 11) Process -- Program, Memory (text, data, bss, heap, stack), execution stack - directly linked to execution function call frame, on the stack CPU -- execution "engine" Early computers:

More information

Pthreads: POSIX Threads

Pthreads: POSIX Threads Shared Memory Programming Using Pthreads (POSIX Threads) Lecturer: Arash Tavakkol arasht@ipm.ir Some slides come from Professor Henri Casanova @ http://navet.ics.hawaii.edu/~casanova/ and Professor Saman

More information

für Mathematik in den Naturwissenschaften Leipzig

für Mathematik in den Naturwissenschaften Leipzig Max-Planck-Institut für Mathematik in den Naturwissenschaften Leipzig Implementation and Usage of a Thread PoolbasedonPOSIXThreads by Ronald Kriemann Technical Report no.: 2 2003 Implementation and Usage

More information

Network Programming TDC 561

Network Programming TDC 561 Network Programming TDC 561 Lecture # 6: Multithreaded Servers Dr. Ehab S. Al-Shaer School of Computer Science & Telecommunication DePaul University Chicago, IL 1 Introduction to Multithreaded Network

More information

TCSS 422: OPERATING SYSTEMS

TCSS 422: OPERATING SYSTEMS TCSS 422: OPERATING SYSTEMS OBJECTIVES Introduction to threads Concurrency: An Introduction Wes J. Lloyd Institute of Technology University of Washington - Tacoma Race condition Critical section Thread

More information

Shared Address Space Programming with Pthreads. CS 5334/4390 Spring 2014 Shirley Moore, Instructor February 18, 2014

Shared Address Space Programming with Pthreads. CS 5334/4390 Spring 2014 Shirley Moore, Instructor February 18, 2014 Shared Address Space Programming with Pthreads CS 5334/4390 Spring 2014 Shirley Moore, Instructor February 18, 2014 1 Topic Overview Thread Basics The POSIX Thread API Mutual Exclusion Locks Condition

More information

HPCSE - I. «Introduction to multithreading» Panos Hadjidoukas

HPCSE - I. «Introduction to multithreading» Panos Hadjidoukas HPCSE - I «Introduction to multithreading» Panos Hadjidoukas 1 Processes and Threads POSIX Threads API Outline Thread management Synchronization with mutexes Deadlock and thread safety 2 Terminology -

More information

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

Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017 Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017 Data Race Shared Data: 465 1 8 5 6 209? tail A[] thread switch Enqueue(): A[tail] = 20; tail++; A[tail] = 9; tail++; Thread 0 Thread

More information

Introduction to PThreads and Basic Synchronization

Introduction to PThreads and Basic Synchronization Introduction to PThreads and Basic Synchronization Michael Jantz, Dr. Prasad Kulkarni Dr. Douglas Niehaus EECS 678 Pthreads Introduction Lab 1 Introduction In this lab, we will learn about some basic synchronization

More information

Parallel Programming with Threads

Parallel Programming with Threads Thread Programming with Shared Memory Parallel Programming with Threads Program is a collection of threads of control. Can be created dynamically, mid-execution, in some languages Each thread has a set

More information

Concurrent Server Design Multiple- vs. Single-Thread

Concurrent Server Design Multiple- vs. Single-Thread Concurrent Server Design Multiple- vs. Single-Thread Chuan-Ming Liu Computer Science and Information Engineering National Taipei University of Technology Fall 2007, TAIWAN NTUT, TAIWAN 1 Examples Using

More information

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

CS 153 Lab4 and 5. Kishore Kumar Pusukuri. Kishore Kumar Pusukuri CS 153 Lab4 and 5 CS 153 Lab4 and 5 Kishore Kumar Pusukuri Outline Introduction A thread is a straightforward concept : a single sequential flow of control. In traditional operating systems, each process has an address

More information

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

Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective? Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective? CS 470 Spring 2019 POSIX Mike Lam, Professor Multithreading & Pthreads MIMD

More information

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

Programming Shared Address Space Platforms (cont.) Alexandre David B2-206 Programming Shared Address Space Platforms (cont.) Alexandre David B2-206 1 Today Finish thread synchronization. Effort for pthreads = synchronization. Effort for MPI = communication. OpenMP. Extra material

More information

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

Oct 2 and 4, 2006 Lecture 8: Threads, Contd Oct 2 and 4, 2006 Lecture 8: Threads, Contd October 4, 2006 1 ADMIN I have posted lectures 3-7 on the web. Please use them in conjunction with the Notes you take in class. Some of the material in these

More information

Pthreads Library Interface. Frank Mueller. Florida State University. phone: (904) , July 22, 1993.

Pthreads Library Interface. Frank Mueller. Florida State University. phone: (904) ,   July 22, 1993. Pthreads Library Interface Frank Mueller Department of Computer Science, B-173 Florida State University Tallahassee, Florida 32306-4019 phone: (904) 644-3441, e-mail: mueller@cs.fsu.edu July 22, 1993 Abstract

More information

Synchronization. Semaphores implementation

Synchronization. Semaphores implementation Synchronization Semaphores implementation Possible implementations There are seeral possible implementations (standard and non standard)of a semaphore Semaphores through pipe POSIX semaphores Linux semaphores

More information

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:

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: CSci 4061: Introduction to Operating Systems (Spring 2013) Final Exam May 14, 2013 (4:00 6:00 pm) Open Book and Lecture Notes (Bring Your U Photo Id to the Exam) This exam paper contains 8 questions (12

More information

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

CS 345 Operating Systems. Tutorial 2: Treasure Room Simulation Threads, Shared Memory, Synchronization CS 345 Operating Systems Tutorial 2: Treasure Room Simulation Threads, Shared Memory, Synchronization Assignment 2 We have a treasure room, Team A and Team B. Treasure room has N coins inside. Each team

More information

Operating System Labs. Yuanbin Wu

Operating System Labs. Yuanbin Wu Operating System Labs Yuanbin Wu CS@ECNU Operating System Labs Project 4 Due: 10 Dec. Oral tests of Project 3 Date: Nov. 27 How 5min presentation 2min Q&A Operating System Labs Oral tests of Lab 3 Who

More information

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

CS 220: Introduction to Parallel Computing. Condition Variables. Lecture 24 CS 220: Introduction to Parallel Computing Condition Variables Lecture 24 Remember: Creating a Thread int pthread_create( pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *),

More information

Multithread Programming. Alexandre David

Multithread Programming. Alexandre David Multithread Programming Alexandre David 1.2.05 adavid@cs.aau.dk Comparison Directive based: OpenMP. Explicit parallel programming: pthreads shared memory focus on synchronization, MPI message passing focus

More information

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

CSCI4430 Data Communication and Computer Networks. Pthread Programming. ZHANG, Mi Jan. 26, 2017 CSCI4430 Data Communication and Computer Networks Pthread Programming ZHANG, Mi Jan. 26, 2017 Outline Introduction What is Multi-thread Programming Why to use Multi-thread Programming Basic Pthread Programming

More information

Lecture 19: Shared Memory & Synchronization

Lecture 19: Shared Memory & Synchronization Lecture 19: Shared Memory & Synchronization COMP 524 Programming Language Concepts Stephen Olivier April 16, 2009 Based on notes by A. Block, N. Fisher, F. Hernandez-Campos, and D. Stotts Forking int pid;

More information

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

POSIX threads CS 241. February 17, Copyright University of Illinois CS 241 Staff POSIX threads CS 241 February 17, 2012 Copyright University of Illinois CS 241 Staff 1 Recall: Why threads over processes? Creating a new process can be expensive Time A call into the operating system

More information

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

CSci 4061 Introduction to Operating Systems. (Threads-POSIX) CSci 4061 Introduction to Operating Systems (Threads-POSIX) How do I program them? General Thread Operations Create/Fork Allocate memory for stack, perform bookkeeping Parent thread creates child threads

More information

Programming RT systems with pthreads

Programming RT systems with pthreads Programming RT systems with pthreads Giuseppe Lipari http://feanor.sssup.it/~lipari Scuola Superiore Sant Anna Pisa December 1, 2011 Outline 1 Timing utilities 2 Periodic threads 3 Scheduler selection

More information

Resource Access Control (2) Real-Time and Embedded Systems (M) Lecture 14

Resource Access Control (2) Real-Time and Embedded Systems (M) Lecture 14 Resource Access Control (2) Real-Time and Embedded Systems (M) Lecture 14 Lecture Outline Resources access control (cont d): Enhancing the priority ceiling protocol Stack-based priority ceiling protocol

More information

Shared Memory Parallel Programming with Pthreads An overview

Shared Memory Parallel Programming with Pthreads An overview Shared Memory Parallel Programming with Pthreads An overview Part II Ing. Andrea Marongiu (a.marongiu@unibo.it) Includes slides from ECE459: Programming for Performance course at University of Waterloo

More information

ENCM 501 Winter 2019 Assignment 9

ENCM 501 Winter 2019 Assignment 9 page 1 of 6 ENCM 501 Winter 2019 Assignment 9 Steve Norman Department of Electrical & Computer Engineering University of Calgary April 2019 Assignment instructions and other documents for ENCM 501 can

More information

pthreads CS449 Fall 2017

pthreads CS449 Fall 2017 pthreads CS449 Fall 2017 POSIX Portable Operating System Interface Standard interface between OS and program UNIX-derived OSes mostly follow POSIX Linux, macos, Android, etc. Windows requires separate

More information

Xu Liu Derived from John Mellor-Crummey s COMP422 at Rice University

Xu Liu Derived from John Mellor-Crummey s COMP422 at Rice University Programming Shared-memory Platforms with Pthreads Xu Liu Derived from John Mellor-Crummey s COMP422 at Rice University Topics for Today The POSIX thread API (Pthreads) Synchronization primitives in Pthreads

More information

Interlude: Thread API

Interlude: Thread API 26 Interlude: Thread API This chapter briefly covers the main portions of the thread API. Each part will be explained further in the subsequent chapters, as we show how to use the API. More details can

More information

11/04/2018. Outline. Process. Process. Pthread Library. Process and threads

11/04/2018. Outline. Process. Process. Pthread Library. Process and threads Outline 1. General descriptions 2. Thread management 3. Scheduler(s) in Linux 4. Time management 5. Handling periodic threads 6. Mutual exclusion 7. Examples Process A process is the main execution entity

More information

Multi-threaded Programming

Multi-threaded Programming Multi-threaded Programming Trifon Ruskov ruskov@tu-varna.acad.bg Technical University of Varna - Bulgaria 1 Threads A thread is defined as an independent stream of instructions that can be scheduled to

More information

Chapter 10. Threads. OS Processes: Control and Resources. A process as managed by the operating system groups together:

Chapter 10. Threads. OS Processes: Control and Resources. A process as managed by the operating system groups together: SFWR ENG 3BB4 Software Design 3 Concurrent System Design 2 SFWR ENG 3BB4 Software Design 3 Concurrent System Design 10.11 13 OS Processes: Control and Resources Chapter 10 Threads A process as managed

More information

Assignment #2. Problem 2.1: airplane synchronization

Assignment #2. Problem 2.1: airplane synchronization Computer Architecture and Operating Systems Course: 320202 Jacobs University Bremen Date: 2009-02-25 Dr. Jürgen Schönwälder, Alen Stojanov Deadline: 2009-03-06 Assignment #2 Problem 2.1: airplane synchronization

More information

CPSC 313: Intro to Computer Systems. POSIX Threads. Latency Hiding / Multiprogramming (covered earlier) Ease of Programming (covered now)

CPSC 313: Intro to Computer Systems. POSIX Threads. Latency Hiding / Multiprogramming (covered earlier) Ease of Programming (covered now) Why Threads? Latency Hiding / Multiprogramming (covered earlier) Ease of Programming (covered now) (R&R, Chapter 12) Thread Management Thread Safety Thread Attributes Why Threads? Latency Hiding / Multiprogramming

More information

Shared Memory Programming Models III

Shared Memory Programming Models III Shared Memory Programming Models III Stefan Lang Interdisciplinary Center for Scientific Computing (IWR) University of Heidelberg INF 368, Room 532 D-69120 Heidelberg phone: 06221/54-8264 email: Stefan.Lang@iwr.uni-heidelberg.de

More information

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

Programming with Shared Memory. Nguyễn Quang Hùng Programming with Shared Memory Nguyễn Quang Hùng Outline Introduction Shared memory multiprocessors Constructs for specifying parallelism Creating concurrent processes Threads Sharing data Creating shared

More information

More Shared Memory Programming

More Shared Memory Programming More Shared Memory Programming Shared data structures We want to make data structures that can be shared by threads. For example, our program to copy a file from one disk to another used a shared FIFO

More information

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

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 Process creation in UNIX All processes have a unique process id getpid(),

More information

Shared Memory: Virtual Shared Memory, Threads & OpenMP

Shared Memory: Virtual Shared Memory, Threads & OpenMP Shared Memory: Virtual Shared Memory, Threads & OpenMP Eugen Betke University of Hamburg Department Informatik Scientific Computing 09.01.2012 Agenda 1 Introduction Architectures of Memory Systems 2 Virtual

More information

CS510 Operating System Foundations. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole CS510 Operating System Foundations Jonathan Walpole Threads & Concurrency 2 Why Use Threads? Utilize multiple CPU s concurrently Low cost communication via shared memory Overlap computation and blocking

More information

High Performance Computing Course Notes Shared Memory Parallel Programming

High Performance Computing Course Notes Shared Memory Parallel Programming High Performance Computing Course Notes 2009-2010 2010 Shared Memory Parallel Programming Techniques Multiprocessing User space multithreading Operating system-supported (or kernel) multithreading Distributed

More information

Lw and ULw POSIX AEPs for Resource Constrained Processors. Document WINNF-14-S-0009

Lw and ULw POSIX AEPs for Resource Constrained Processors. Document WINNF-14-S-0009 Lw and ULw POSIX AEPs for Resource Constrained Processors Document WINNF-14-S-0009 Version V1.0.0 25 July 2014 TERMS, CONDITIONS & NOTICES This document has been prepared by the work group of WInnF project

More information

PThreads in a Nutshell

PThreads in a Nutshell PThreads in a Nutshell Chris Kauffman CS 499: Spring 2016 GMU Logistics Today POSIX Threads Briefly Reading Grama 7.1-9 (PThreads) POSIX Threads Programming Tutorial HW4 Upcoming Post over the weekend

More information

Concurrent Programming

Concurrent Programming Concurrent Programming Prof. Jinkyu Jeong( jinkyu@skku.edu) TA Jinhong Kim( jinhong.kim@csl.skku.edu) TA Seokha Shin(seokha.shin@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu

More information

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

The course that gives CMU its Zip! Concurrency I: Threads April 10, 2001 15-213 The course that gives CMU its Zip! Concurrency I: Threads April 10, 2001 Topics Thread concept Posix threads (Pthreads) interface Linux Pthreads implementation Concurrent execution Sharing data

More information

Threads. studykorner.org

Threads. studykorner.org Threads Thread Subpart of a process Basic unit of CPU utilization Smallest set of programmed instructions, can be managed independently by OS No independent existence (process dependent) Light Weight Process

More information

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

Unix. Threads & Concurrency. Erick Fredj Computer Science The Jerusalem College of Technology Unix Threads & Concurrency Erick Fredj Computer Science The Jerusalem College of Technology 1 Threads Processes have the following components: an address space a collection of operating system state a

More information

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

Concurrency and Synchronization. ECE 650 Systems Programming & Engineering Duke University, Spring 2018 Concurrency and Synchronization ECE 650 Systems Programming & Engineering Duke University, Spring 2018 Concurrency Multiprogramming Supported by most all current operating systems More than one unit of

More information

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

CSE 421/521 - Operating Systems Fall 2011 Recitations. Recitation - III Networking & Concurrent Programming Prof. Tevfik Kosar. Presented by... CSE 421/521 - Operating Systems Fall 2011 Recitations Recitation - III Networking & Concurrent Programming Prof. Tevfik Kosar Presented by... University at Buffalo September..., 2011 1 Network Programming

More information

Faculté Polytechnique

Faculté Polytechnique Faculté Polytechnique Real-Time Systems - Practical Work 5 POSIX Threads Dr Frémal Sébastien Sebastien.FREMAL@umons.ac.be Ir Michel Bagein Michel.BAGEIN@umons.ac.be Prof. Pierre Manneback Pierre.MANNEBACK@umons.ac.be

More information

Locks and semaphores. Johan Montelius KTH

Locks and semaphores. Johan Montelius KTH Locks and semaphores Johan Montelius KTH 2017 1 / 41 recap, what s the problem : # include < pthread.h> volatile int count = 0; void * hello ( void * arg ) { for ( int i = 0; i < 10; i ++) { count ++;

More information

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

CS Lecture 3! Threads! George Mason University! Spring 2010! CS 571 - Lecture 3! Threads! George Mason University! Spring 2010! Threads! Overview! Multithreading! Example Applications! User-level Threads! Kernel-level Threads! Hybrid Implementation! Observing Threads!

More information