210 likes | 359 Views
Multi-threaded Programming with P OSIX Threads. CSE331 Operating Systems Design. Text. Data. Stack1. Stack2. Thread1. Thread2. Processes vs Threads. Text. Text. Data. Data. Stack. Stack. Process1. Process2. Some Terms. Thread Safe Reentrant Multi-threaded POSIX.
E N D
Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design
Text Data Stack1 Stack2 Thread1 Thread2 Processes vs Threads Text Text Data Data Stack Stack Process1 Process2
Some Terms • Thread Safe • Reentrant • Multi-threaded • POSIX
What does POSIX mean? • Portable Operating System Interface for Unix" is the name of a family of related standards specified by the IEEE to define the application programming interface (API), along with shell and utilities interfaces, for software compatible with variants of the UNIX operating system, although the standard can apply to any operating system.
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_destroy() • pthread_mutex_lock() • pthread_mutex_trylock() • pthread_mutex_unlock()
pthread API’s cont’d • 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_getprotocol() • pthread_mutexattr_setprotocol() • pthread_setschedparam() • pthread_attr_setschedpolicy() • sched_get_priority_max() • sched_set_priority_min()
#include <pthread.h>#include <stdio.h>void *thread_routine(void* arg){ printf("Inside newly created thread \n");}void main(){ pthread_t thread1; pthread_create(&thread1, NULL, thread_routine, NULL); pthread_create( &thread_id, NULL, thread_routine, NULL );printf("Inside main thread \n"); pthread_join( thread_id, NULL );}pluto.nvc.cs.vt.edu$ cc p.c -lpthread
int pthread_create( pthread_t *tid, //Thread ID returned by the systemconst pthread_attr_t *attr, //optional attributesvoid *(*start)(void *), //thread functionvoid *arg // Arguments to start function);Description: Create a thread running the start function.
int pthread_join( pthread_t thread, // ID of threadvoid **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.
intpthread_exit( void *value_ptr, // Return value);Description: Terminate the calling thread, returning the value value_ptr to any joining thread.intpthread_equal( pthread_t t1, // ID of thread1pthread_t t2, // ID of thread2 );Description: Return zero if equal.Non-zero if not.
intpthread_cancel( pthread_t threadID// 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_tpthread_self();Description: Used to get the ID of the current thread.intsched_yield();Description: Make the calling thread from running state to ready state, giving way for other threads.
Thread Cancellation 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");}
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 you 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 • pthread_mutex_init() • pthread_mutex_destroy() • pthread_mutex_lock() • pthread_mutex_trylock() • pthread_mutex_unlock()
Reasons for Synchronization Need • For getting shared access to resources (variables, buffers, devices, etc.) • Critical variables; critical sections. • For communicating. • Cases where cooperating processes need not synchronize to share resources: • All processes are read only. • All processes are write only. • One process writes (atomically), all other processes read.
Atomicity • What does atomic mean? • Characteristics of ‘trouble situations’: • Multiple processes doing updates non-atomically. • Non-atomic write processes coupled with read or update processes
void *consumer(void* arg){for(int I =0; I < 30 ; I ++ )mutex );, shared_data--; /* Critical Section. */ printf("dataval=%d\n”, shared_data);} void main(){ pthread_t thread_id; pthread_create(&thread_id, NULL, consumer, NULL); for(int I =0; I < 30 ; I ++ ) shared_data ++; /* Critical Section. */ printf("End of main =%d\n”, shared_data);}
Formal Definition of Critical Sections • The overlapping portion of each process, where the shared variables are being accessed. • Necessary and sufficient conditions for a solution to the critical section problem: • Mutual Exclusion • Progress • Bounded Waiting
Mutual Exclusion Simplest and most efficient thread synchronization mechanism • A special variable that can be either in • locked state: a distinguished thread that holds or owns the mutex; or • unlocked state: no thread holds the mutex • When several threads compete for a mutex, one wins. The rest block at that call • The mutex also has a queue of threads that are waiting to hold the mutex. • POSIX does not require that this queue be accessed FIFO
POSIX Mutex-related Functions • int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr); • Also see PTHREAD_MUTEX_INITIALIZER • int pthread_mutex_destroy(pthread_mutex_t *mutex); • int pthread_mutex_lock(pthread_mutex_t *mutex); • int pthread_mutex_trylock(pthread_mutex_t *mutex); • int pthread_mutex_unlock(pthread_mutex_t *mutex);
Example #include <pthread.h> #include <stdio.h> #include <stdlib.h> static pthread_mutex_t my_lock = PTHREAD_MUTEX_INITIALIZER; void *mythread(void *ptr) { long int i,j; while (1) { pthread_mutex_lock (&my_lock); for (i=0; i<10; i++) { printf ("Thread %d\n", (int) ptr); for (j=0; j<50000000; j++); } pthread_mutex_unlock (&my_lock); for (j=0; j<50000000; j++); } } int main (int argc, char *argv[]) { pthread_t thread[2]; pthread_create(&thread[0], NULL, mythread, (void *)0); pthread_create(&thread[1], NULL, mythread, (void *)1); getchar(); }