Programming with Posix Threads CS5204 Operating Systems.

Slides:



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

Threads Programming Thread creation Synchronization.
1 Threads. 2 Real Life Example?  Process  “system programming” course  Different from “internet engineering”  Thread  homework, Reading, Self-assessment.
Pthreads & Concurrency. Acknowledgements  The material in this tutorial is based in part on: POSIX Threads Programming, by Blaise Barney.
Multi-core Programming Programming with Posix Threads.
PTHREADS These notes are from LLNL Pthreads Tutorial
Threads Lab اللهم علمنا ما ينفعنا،،، وانفعنا بما علمتنا،،، وزدنا علماً
Chap. 23 Threads (1) Threads v.s. Fork (2) Basic Thread Functions #include int pthread_create ( pthread_t *tid, const pthread_attr_t *attr, void *(*func)(void.
Computer Architecture II 1 Computer architecture II Programming: POSIX Threads OpenMP.
Pthreads Operating Systems Hebrew University of Jerusalem Spring 2004.
8-1 JMH Associates © 2004, All rights reserved Windows Application Development Chapter 10 - Supplement Introduction to Pthreads for Application Portability.
Lecture 18 Threaded Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
B.Ramamurthy1 POSIX Thread Programming 2/14/97 B.Ramamurthy.
Unix Threads operating systems. User Thread Packages pthread package mach c-threads Sun Solaris3 UI threads Kernel Threads Windows NT, XP operating systems.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
Pthread II. Outline Join Mutex Variables Condition Variables.
Comp 422: Parallel Programming Shared Memory Multithreading: Pthreads Synchronization.
Netprog Threads Programming1 Threads Programming Refs: Chapter 23.
THREAD IMPLEMENTATION For parallel processing. Steps involved Creation Creates a thread with a thread id. Detach and Join All threads must be detached.
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.
Portable Operating System Interface Thread Yukai Hung Department of Mathematics National Taiwan University Yukai Hung
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.
POSIX Threads Nezer J. Zaidenberg. References  Advanced programming for the UNIX environment (2nd edition chapter This material does not exist.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
Copyright ©: University of Illinois CS 241 Staff1 Synchronization and Semaphores.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
Programming with POSIX* Threads Intel Software College.
Condition Variables u A condition variable is used to wait until a particular condition is true  like in a monitor u Always use condition variables together.
Professor: Shu-Ching Chen TA: Samira Pouyanfar.  An independent stream of instructions that can be scheduled to run  A path of execution int a, b; int.
Pthreads: A shared memory programming model
CSC Advanced Unix Programming, Fall, 2008 Monday, November 24 POSIX threads (pthreads)
S -1 Posix Threads. S -2 Thread Concepts Threads are "lightweight processes" –10 to 100 times faster than fork() Threads share: –process instructions,
Threads and Locking Ioctl operations. Threads Lightweight processes What’s wrong with processes? –fork() is expensive – 10 to 100 times slower –Inter.
Threads Chapter 26. Threads Light-weight processes Each process can have multiple threads of concurrent control. What’s wrong with processes? fork() is.
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.
POSIX Synchronization Introduction to Operating Systems: Discussion Module 5.
Pthreads.
Pthreads #include pthread_t tid ; //thread id. pthread_attr_t attr ; void *sleeping(void *); /* thread routine */ main() { int time = 2 ; pthread_create(&tid,
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Software Systems Advanced Synchronization Emery Berger and Mark Corner University.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Unix System Calls and Posix Threads.
Chapter 6 P-Threads. Names The naming convention for a method/function/operation is: – pthread_thing_operation(..) – Where thing is the object used (such.
Unix Internals Concurrent Programming. Unix Processes Processes contain information about program resources and program execution state, including: Process.
Copyright ©: Nahrstedt, Angrave, Abdelzaher
PThread Synchronization. Thread Mechanisms Birrell identifies four mechanisms commonly used in threading systems –Thread creation –Mutual exclusion (mutex)
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
POSIX THREADS. What is a thread? Multiple stands of execution in a single program are called threads. In other words, a thread is a sequence of control.
Working with Pthreads. Operations on Threads int pthread_create (pthread_t *thread, const pthread_attr_t *attr, void * (*routine)(void*), void* arg) Creates.
COMP7330/7336 Advanced Parallel and Distributed Computing POSIX Thread API Dr. Xiao Qin Auburn University
回到第一頁 What are threads n Threads are often called "lightweight processes” n In the UNIX environment a thread: u Exists within a process and uses the process.
Case Study: Pthread Synchronization Dr. Yingwu Zhu.
Tutorial 4. In this tutorial session we’ll see Threads.
PThreads.
Principles of Operating Systems Lecture 11
Threads in C Caryl Rahn.
Shared-Memory Programming with Threads
Threads Threads.
Netprog: Threads Programming
Copyright ©: Nahrstedt, Angrave, Abdelzaher
PTHREADS These notes are from LLNL Pthreads Tutorial
Multithreading Tutorial
Operating Systems Lecture 13.
Multithreading Tutorial
Thread Programming.
Pthread Prof. Ikjun Yeom TA – Mugyo
Multithreading Tutorial
Multithreading Tutorial
Tutorial 4.
POSIX Threads(pthreads)
Presentation transcript:

Programming with Posix Threads CS5204 Operating Systems

Processes vs. Threads Stack Data Text Process1 Stack Data Text Process2 Stack2 Data Text Thread1 Stack1 Thread2

Some Terms Thread Safe Reentrant Multi-threaded

Commonly used pThread API’s pthread_create( ) pthread_detach( ) pthread_equal( ) pthread_exit( ) pthread_join( ) pthread_self( ) sched_yield( ) pthread_cancel() pthread_mutex_init() pthread_mutex_destro y() pthread_mutex_lock() pthread_mutex_tryloc k() pthread_mutex_unlock ()

pThread API’s contd….. pthread_cond_destroy( ) pthread_cond_init( ) pthread_cond_broadcast( ) pthread_cond_signal( ) pthread_cond_timedwait() pthread_cond_wait() pthread_mutexattr_gettype pthread_mutexattr_settype pthread_setconcurrency() pthread_getconcurrency() pthread_mutexattr_getprot ocol pthread_mutexattr_setprot ocol pthread_setschedparam pthread_attr_setschedpolic y sched_get_priority_max sched_set_priority_min

Thread State Transitions Ready Blocked Running Terminated Done or cancelled Wait for resource Wait satisfied Preempted Scheduled Start

#include #include void *thread_routine(void* arg){ printf("Inside newly created thread \n"); } void main(){ pthread_t thread_id; void *thread_result; pthread_create( &thread_id, NULL, thread_routine, NULL ); printf("Inside main thread \n"); pthread_join( thread_id, &thread_result ); } pluto.nvc.cs.vt.edu$ cc p.c -lpthread

/////////////////////////////// Join Example:- #include #include #include void *thread_routine(void* arg){ printf("Inside newly created thread \n"); return (void*) strdup("Thread return value string"); } void main(){ pthread_t thread_id; void *thread_result =0; pthread_create( & thread_id, NULL, thread_routine, NULL ); printf("Inside main thread \n"); pthread_join( thread_id, &thread_result ); if ( thread_result != 0 ) printf("In main %s\n", thread_result ); }

int pthread_create( pthread_t *tid, // Thread ID returned by the system const pthread_attr_t *attr, // optional creation attributesvoid *(*start)(void *), // start function of the new threadvoid *arg // Arguments to start function ); Description: Create a thread running the start function.

int pthread_exit( void *valud_ptr, // Return value. ); Description: Terminate the calling thread, returning the value value_ptr to any joining thread. int pthread_equal( pthread_t t1, // ID of thread1 pthread_t t2, // ID of thread2 ); Description: Return zero if equal. Non-zero if not.

int pthread_join( pthread_t thread, // ID of thread void **value_ptr // return value of thread ); Description: Wait for thread to terminate, and return thread’s exit value if value_ptr is not NULL. This also detaches thread on successful completion. int pthread_detach( pthread_t thread, // ID of thread to detach ); Description: Does not terminate a thread. Storage is freed immediately on termination. Detached threads Cannot be joined or canceled.

int pthread_cancel( pthread_t thread, // ID of thread to cancel ); Description: Cancellation provides a way to request that a thread terminate gracefully when you no longer need it to complete its normal execution. Each thread can control how and whether cancellation affect it and repair the shared state as it terminates due to cancellation. pthread_t pthread_self( ); Description: Used to get the ID of the current thread. int sched_yield( ); Description: Make the calling thread from running state to ready state, giving way for other threads.

//////////////////////////////////// Cancel Example:- void *thread_routine(void* arg){ printf("Inside thread \n"); sleep( 30 ); printf("After sleep \n"); } void main(){ pthread_t thread_id; void *thread_result =0; pthread_create( & thread_id, NULL, thread_routine, NULL ); sleep(3); printf("Main thread\n"); pthread_cancel( thread_id ); printf("End of main\n"); }

Some facts * If multiple threads want to wait for the completion of a thread, they cannot do so by calling pthread_join(), Instead these threads should wait on a condition variable which is set by the waited thread after completion. * Main thread vs Other Threads 1) Input arguments are different. 2) When main thread returns all other threads are aborted. 3) If u want the main thread to exit, but other threads to keep running then call pthread_exit in the main function. * Avoid fork and signals in threads.

Synchronization(Mutexes) pthread_mutex_init() pthread_mutex_destroy() pthread_mutex_lock() pthread_mutex_trylock() pthread_mutex_unlock()

pthread_mutex_t mutex=PTHREAD_MUTEX_INITILIZER; int shared_data =1; void *consumer(void* arg) { for(int I =0; I < 30 ; I ++ ){ pthread_mutex_lock( &mutex ); shared_data--; /* Critical Section. */ pthread_mutex_unlock( &mutex ); } printf("Returning from Comsumer =%d\n”, shared_data); } void main() { pthread_t thread_id; pthread_create( & thread_id, NULL, consumer, NULL ); for(int I =0; I < 30 ; I ++ ){ pthread_mutex_lock( &mutex ); shared_data ++; /* Producer Critical Section. */ pthread_mutex_unlock( &mutex ); } /*pthread_exit(0); /* Return from main thread. */ printf("End of main =%d\n”, shared_data); }

int pthread_mutex_lock( pthread_mutex_t*mutex ); Description: Lock a mutex. If the mutex is currently locked, the calling thread is blocked until mutex is unlocked. On return, the thread owns the mutex until it calls pthread_mutex_unlock. int pthread_mutex_trylock( pthread_mutex_t*mutex ); Description: Lock a mutex. If the mutex is currently locked, returns immediately with EBUSY. Otherwise, calling thread becomes owner until it unlocks.

int pthread_mutex_unlock( pthread_mutex_t*mutex ); Description: UnLock a mutex. The mutex becomes unwoned. If any threads are waiting for the mutex, one is awakened(scheduling policy SCHED_FIFO and SCHED_RR policy waiters are chosen in priority order, then any others are chosen in unspecified order.

int pthread_mutex_init( pthread_mutex_t*mutex, const pthread_mutexattr_t * attr ); Description: Initialize a mutex. The attr argument specifies optional creation attributes. int pthread_mutex_destroy( pthread_mutex_t*mutex ); Description: Destroy a mutex that you no longer need.

Producer-Consumer example

pthread_mutex_t read_mutex=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t w_mutex=PTHREAD_MUTEX_INITIALIZER; #define QUEUE_SIZE 10 #define ITERATIONS 1000 int in =0, out =0; int shared_data =1; int n_consumer =0; int queue_is_empty(){ if ( in == out ) return 1; else return 0 ; } int queue_is_full(){ if ( in == (out+1 %QUEUE_SIZE) ) return 1; else return 0 ; } void main() {pthread_t thread_id; pthread_create(&thread_id,NULL, consumer, NULL); pthread_create(&thread_id,NULL, consumer, NULL); sleep(5); pthread_create(&thread_id,NULL, producer, NULL); pthread_create(&thread_id,NULL, producer, NULL); pthread_exit(0); }

void *consumer(void* arg){ int i; n_consumer ++; for (i =0; i < ITERATIONS; ) { if (queue_is_empty()){sched_yield(); continue;} pthread_mutex_lock( &read_mutex ); if ( queue_is_empty() ){ pthread_mutex_unlock(&read_mutex); continue; } /*read from queue[ in ] */ in = (in +1) % QUEUE_SIZE; pthread_mutex_unlock( &read_mutex ); i++; } printf("Returning from Comsumer\n"); n_consumer --; }

void *producer(void* arg ) { int i; for (i =0; n_consumer; i ++) { if (queue_is_full()) {sched_yield();continue;} pthread_mutex_lock( &w_mutex ); if ( queue_is_full() ){ pthread_mutex_unlock(&w_mutex ); continue; } /* write to queue[out] */ out = (out +1) % QUEUE_SIZE; pthread_mutex_unlock( &w_mutex ); } printf("Returning from Producer\n"); }

int pthread_cond_init( pthread_cond_t*cond, const pthread_condattr_t *attr ); Description: Initialize a condition variable cond. The attr argument specifies optional creation attributes. int pthread_cond_destroy( pthread_cond_t*cond ); Description: Destroy condition variable cond that you no longer need.

int pthread_cond_wait( pthread_cond_t*cond, pthread_mutex_t *mutex ); Description: Wait on condition variable cond, until awakened by a signal or broadcast. int pthread_cond_signal( pthread_cond_t*cond ); Description: Signal condition variable cond, walking one waiting thread. If SCHED_FIFO or SCHED_RR policy threads are waiting, the highest priority waiter is awakened. Otherwise an unspecified waiter is awakened.

int pthread_cond_timedwait( pthread_cond_t*cond, pthread_mutex_t *mutex, const struct timespec *abstime ); Description: Wait on condition variable cond, until awakened by a signal or broadcast or until the absolute time abstime is reached. int pthread_cond_broadcast( pthread_cond_t*cond ); Description: Broadcast condition variable cond, waking all current waiters.

Producer-Consumer using condition wait //Initializations pthread_mutex_t read_mutex=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t write_mutex=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t qempty_cond_mutex=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t q_notempty_cond =PTHREAD_COND_INITIALIZER; pthread_mutex_t qfull_cond_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t q_notfull_cond = PTHREAD_COND_INITIALIZER;

void *consumer(void* arg) { int i; n_consumer ++; for (i =0; i < ITERATIONS; i++) { pthread_mutex_lock( &read_mutex ); while ( queue_is_empty() ){ pthread_cond_wait(& q_notempty_cond, &qempty_cond_mutex ); } /*read from queue[ in ] */ in = (in +1) % QUEUE_SIZE; pthread_mutex_unlock( &read_mutex ); pthread_cond_signal(&q_notfull_cond); } printf("Returning from Comsumer\n"); n_consumer --; }

void *producer(void* arg ) { int i; for (i =0; n_consumer; i ++) { pthread_mutex_lock( &write_mutex ); while ( queue_is_full() ){ pthread_cond_wait(&q_notfull_cond, &qfull_cond_mutex ); } /* write to queue[out] */ out = (out +1) % QUEUE_SIZE; pthread_mutex_unlock( &write_mutex ); pthread_cond_signal(& q_notempty_cond ); } printf("Returning from Producer\n"); }

Attributes for pthreads & mutex. * detach state, stack size, stack addr, cancel state, cancel type, get/set sched policy and param, inheritedsched. Priority aware mutexes, get/set protocol, prioceiling

Pthread_attr_t thread_attr; pthread_attr_init(&thread_attr); size_t stack_size; pthread_attr_getstacksize(&thread_attr, &stack_size ); int status = pthread_attr_setsstacksize(&thread_attr, stack_size * 1.5 ); if ( status != 0 ) { /// handle error } pthread_create( & thread_id, & thread_attr, thread_routine, “Arg1” );

References Programming with Posix threads- David R. Butenhof( ) Download source code from puting. Unix man pages