Pthreads – Create and Join

Slides:



Advertisements
Similar presentations
CS Lecture 4 Programming with Posix Threads and Java Threads George Mason University Fall 2009.
Advertisements

Multi-core Programming Programming with Posix Threads.
CS427 Multicore Architecture and Parallel Computing
Multiprocessors and Multi-computers Multi-computers –Distributed address space accessible by local processors –Requires message passing –Programming tends.
Threads By Dr. Yingwu Zhu. Review Multithreading Models Many-to-one One-to-one Many-to-many.
Threads? Threads allow us to have multiple tasks active at the same time in one executable –think of a server handling multiple connections Each thread.
CS 241 Section Week #4 (2/19/09). Topics This Section  SMP2 Review  SMP3 Forward  Semaphores  Problems  Recap of Classical Synchronization Problems.
Multithreaded Web Server.
Introduction to Pthreads. Pthreads Pthreads is a POSIX standard for describing a thread model, it specifies the API and the semantics of the calls. Model.
The University of Adelaide, School of Computer Science
04/10/25Parallel and Distributed Programming1 Shared-memory Parallel Programming Taura Lab M1 Yuuki Horita.
Operating Systems CMPSC 473 Multi-threading models Tutorial on pthreads Lecture 10: September Instructor: Bhuvan Urgaonkar.
Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
What is a thread? process: an address space with 1 or more threads executing within that address space, and the required system resources for those threads.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Semaphore and Mutex Operations.
Programming with POSIX* Threads Intel Software College.
Pthreads: A shared memory programming model
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
Thread API Xiaohua Lu Office : CS 3310 Tel. : Office hours: 11-12,3-5 T,TR.
Lecture 5 Barriers and MPI Introduction Topics Barriers Uses implementations MPI Introduction Readings – Semaphore handout dropboxed January 24, 2012 CSCE.
POSIX Synchronization Introduction to Operating Systems: Discussion Module 5.
(p)Threads Libraries Math 442 es Jim Fix. Life cycle of a thread.
POSIX Threads HUJI Spring 2011.
Pthreads.
2.3 interprocess communcation (IPC) (especially via shared memory & controlling access to it)
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 11: Thread-safe Data Structures, Semaphores.
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 12: Thread-safe Data Structures, Semaphores.
Chapter 6 P-Threads. Names The naming convention for a method/function/operation is: – pthread_thing_operation(..) – Where thing is the object used (such.
Copyright ©: Nahrstedt, Angrave, Abdelzaher
PThread Synchronization. Thread Mechanisms Birrell identifies four mechanisms commonly used in threading systems –Thread creation –Mutual exclusion (mutex)
Working with Pthreads. Operations on Threads int pthread_create (pthread_t *thread, const pthread_attr_t *attr, void * (*routine)(void*), void* arg) Creates.
Real-Time Threads Time dependent, usually wrt deadline –Periodic –Aperiodic –Sporadic Priority scheduled Fault tolerant.
1 Programming with Shared Memory - 2 Issues with sharing data ITCS 4145 Parallel Programming B. Wilkinson Jan 22, _Prog_Shared_Memory_II.ppt.
CS 311/350/550 Semaphores. Semaphores – General Idea Allows two or more concurrent threads to coordinate through signaling/waiting Has four main operations.
Case Study: Pthread Synchronization Dr. Yingwu Zhu.
Synchronization and Semaphores
CS 537 – Introduction to Operating Systems
C Threads and Semaphores
Lesson One – Creating a thread
Principles of Operating Systems Lecture 11
Shared Memory Programming with Pthreads
סמפורים.
Threads in C Caryl Rahn.
Shared-Memory Programming with Threads
Threads Threads.
Boost String API & Threads
POSIX Threads 1. Background 2. Threads vs. Processes
Multithreading Tutorial
CSE 333 – Section 9 Threads.
PTHREADS AND SEMAPHORES
The University of Adelaide, School of Computer Science
The University of Adelaide, School of Computer Science
BOOM! count is [ ], should be
Synchronization and Semaphores
The University of Adelaide, School of Computer Science
Pthread Prof. Ikjun Yeom TA – Mugyo
Operating System Concepts
Programming with Shared Memory
Synchronization Primitives – Semaphore and Mutex
Realizing Concurrency using Posix Threads (pthreads)
Programming with Shared Memory
Synchronization.
Programming with Shared Memory - 2 Issues with sharing data
Synchronization.
Lecture 20: Synchronization
Shared Memory Programming with Pthreads
POSIX Threads(pthreads)
Lab #9 Semaphores Operating System Lab.
Presentation transcript:

Pthreads – Create and Join IEEE Portable Operating System Interface Standard (POSIX) Spawn an attached thread pthread_create (&thread1, NULL, proc1, &arg) . pthread_join(thread1, status) Thread execution void proc1(&arg) { // Thread code return(*status); } Detatched threads Join is not needed The OS destroys thread resources when they terminate A parameter in the create call indicates a detached thread Note: The Pthreads library must be available : #include <pthread.h>

Executing a Thread

Locks Declare a lock: pthread_mutex_t mutex; Declare a mutex attribute: pthread_mutexattr_t mta; Initializing an attribute (spin_only, limited_spin, no_spin, recursive, metered) pthread_mutexattr_init(&mta); pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE); pthread_mutexattr_setname_np(&mta, "My Mutex"); Initialize a mutex pthread_mutex_init(&mutex, NULL); // Use defaults pthread_mutex_init(&mutex, &mta); // or use designated attributes Enter and release Pthread_mutex_lock(&mutex); and pthread_mutex_unlock(&mutex); Try Lock without block: pthread_mutex_trylock(&mutex); Release resources pthread_mutex_destroy(mutex); and pthread_mutexattr_destroy(&mta);

Semaphores Initialize Required: # include <semaphore . h> Semaphores are not part of Pthreads Initialize int sem_init ( sem_t *sem, int shared, /* non-zero to share between processes */ unsigned initial_val ) ; /* one works like a mutex */ Destroy semaphore: int sem_destroy ( sem_t sem) ; Post (V): int sem_post ( sem_t sem ) ; Wait (P): int sem_wait ( sem_t sem ) ; Semaphores can count up or down and can start with any positive integer value

Condition Variables counter() { . . pthread_mutex_lock(&mutex); c--; if (c == 0) pthread_cond_signal(cond); . . pthread_mutex_unlock(&mutex); } action() { . . pthread_mutex_lock(&mutex); while (c <> 0) pthread_cond_wait(cond,mutex); pthread_mutex_unlock(&mutex); take_action(); } Note: Signals are missed if a thread is not waiting when they are sent

Read-Write Locks Initialize Locking More than reader is allowed, however, writing is exclusive Initialize int pthread_rwlock_init (pthread_rwlock_t *readWriteLock , const pthread_rwlockattr_t attr_p ) ; Locking i n t pthread_rwlock_rdlock( pthread_rwlock_t readWriteLock ) ; i n t pthread_rwlock_wrlock( pthread_rwlock_t readWriteLock ) ; Unlock: int pthread_rwlock_unlock( pthread_rwlock_t readWriteLock ) ; Destroy: int pthread_rwlock_destroy ( pthread_rwlock_t readWriteLock ) ; Practical Example: Multithreaded linked lists or binary trees

Hello World: Pthreads Make sure to include: <stdio.h>, <stdlib.h>, and <pthread.h> void* Hello ( void* myRank ) { printf ( "Hello from thread %ld\n" , (long)(*myRank) ) ; return NULL ; } void main ( int argc , char argv [ ] ) { long t; pthread_t[] threadHandles ; int threads = strtol ( argv [ 1 ] , NULL , 1 0 ) ; thread_handles = malloc ( threads * sizeof( pthread_t ) ) ; for ( t = 0 ; t< threads; t ++ ) pthread_create(&threadHandles [ t ] , NULL ,Hello , ( void *) &t ); printf ( "Hello from the main thread\n" ) ; for ( t= 0 ; t < threads; t ++) pthread_join ( threadHandles [ t ] , NULL ) ; free( threadHandles ) ;

Matrix Multiplication Pthreads Version Matrix Multiplication void* matrixMult( void *rank ) { i nt r, c , myM = m / (int)threads ; long myRank = (long)(*rank); int startRow = myRank * myM ; int lastRow = (rank+1) * myM − 1 ; for ( r = startRow ; r <= lastRow ; r++) { y[r] = 0 . 0 ; for ( c = 0 ; c < n ; c++) y[ r ] += A[r][c] x[c] ; } return NULL ; Sequential Version for ( r = 0 ; r < m ; r++) { y [ r ] = 0.0 ; for ( c = 0 ; c < n ; c++) y[ r ] += A[ r][ c] * x[ c ] ; } Assumption: Even number of rows per processor and m, n, threads are global variables Note: Works because we don't alter the original data

Failed Pthread version Calculate π Calculation of π Failed Pthread version π = 4(1-1/3+1/5-1/7+ … ) Sequential version double factor = 1.0, sum = 0.0; for (i=0; i<n; i++, factor = -factor) { sum += factor/2*i+1; } pi = 4*sum; void* Thread_sum ( void *rank ) { long myRank = ( long ) (*rank) ; double factor ; long long i, myN = n/threads; long long first = myN*myRank long long last = first+myN; if ( first % 2 == 0) factor = 1 . 0 ; else factor = −1.0; for ( i=first; i<last ; i++, factor =−factor ) { sum += factor / ( 2*i + 1 ) ; } } The statement that updates sum is a critical section

Busy Wait Solutions Update sum in the loop Sum after the loop void* Thread_sum ( void *rank ) { long myRank = ( long ) (*rank) ; double factor, sum=0; long long i, myN = n/threads; long long first = myN*myRank; long long last = first + myN; if ( first % 2 == 0) factor = 1 . 0 ; else factor = −1.0; for (i=first; i<last ; i++,factor=-factor) { while (flag !=myRank); sum += factor / ( 2*i + 1 ) ; flag = (flag+1)%threads; } } void* Thread_sum ( void *rank ) { long myRank = ( long ) (*rank) ; double factor, mySum=0.0; long long i, myN = n/threads; long long first = myN*myRank; if ( first % 2 == 0) factor = 1.0; e l s e factor = −1.0; for (i=first;i<first+myN;i++,factor=−factor) { mySum += factor / ( 2*i + 1 ) ; } while (flag !=myRank); sum += mySum; flag = (flag+1)%threads; }

MUTEX Solution Time Comparison void* Thread_sum ( void *rank ) { long myRank = ( long ) (*rank) ; double factor, mySum=0; long long i, myN = n/threads; long long first = myN*myRank, first+myN; if ( first % 2 == 0) factor = 1 . 0 ; e l s e factor = −1.0; f o r (i=first; i<last ; i++, factor =−factor) { mySum += factor / ( 2*i + 1 ) ; } pthread_mutex_lock(&mutex) sum += mySum; pthread_mutex_unlock(&mutex); } Time Comparison Busy wait slower, but order of execution is deterministic

Sending Messages to Threads Each Processor stores a message to the next array index Solution with Mutexes is not obvious Initialize the Semaphores to 0 (locked), then unlock before lock Failure: Critical Section Solution with Semaphores void* Send_msg ( void* arg ) { long rank = ( long )(*arg) ; long to = (rank+1)%threads ; char *msg=malloc (MAX*sizeof (char)) ; sprintf (msg ,"%ld --> %ld, rank, to) ; msgs[ to ] = msg ; printf ("%ld>%s\n",rank,msgs[rank]) ; } void* Send_msg ( void* arg ) { long rank = ( long ) (*arg) ; long to = (rank+1)%threads ; char *msg = malloc(MAX*sizeof(char)); sprintf (msg, %ld --> %ld", rank, to) ; msgs[ to ] = msg ; sem_post(&semaphores [ to] ) ; sem_wait(&semaphores [ rank ] ) ; printf (%ld > %s\n", rank , msgs[rank ] ) ; }

Barriers: Condition variables Note: Pthreads does provide for barriers /* Shared */ int counter = 0 ; pthread_mutex_t mtx ; pthread_cond_t cnd ; /* . . . Thread work */ /* Start of the barrier */ pthread_mutex_lock(&mtx ) ; counter ++; i f ( counter == threads) { counter = 0 ; pthread_cond_broadcast(&cnd ) ; } else { while (pthread_cond_wait(&cnd,&mtx)!=0); } pthread_mutex_unlock(&mtx ) ; /* More thread work . . . */ Barriers: Mutex int thread_count ; pthread_mutex_t mtx; /* . . . Thread work */ /* Start of the barrier */ pthread_mutex_lock(&mtx ) ; counter ++; pthread_mutex_unlock(&mtx) ; while ( counter < thread_count ) ; . . . } // Inefficient (busy-wait ) /* More thread work . . . */

Read-Write Locks and Lists Accessing the list pthread_rwlock_rdlock(&rwlock ) ; entry = Find( key ) ; pthread_rwlock_unlock(&rwlock ) ; Inserting into the list pthread_rwlock_wrlock(&rwlock ) ; Insert ( entry ) ; Removing from the list Delete ( entry ) ;