Presentation is loading. Please wait.

Presentation is loading. Please wait.

Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design.

Similar presentations

Presentation on theme: "Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design."— Presentation transcript:

1 Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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

3 Some Terms Thread Safe Reentrant Multi-threaded POSIX

4 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.

5 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()

6 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()

7 #include #include 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 ); }$ cc p.c -lpthread

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

9 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.

10 int pthread_exit( void *value_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.

11 int pthread_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_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.

12 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"); }

13 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.

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

15 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.

16 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

17 void *consumer(void* arg) { for(int I =0; I < 30 ; I ++ )mutex );,shared_data--; /* Critical Section. */ printf("data val=%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); }

18 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

19 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

20 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);

21 Example #include 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(); }

Download ppt "Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design."

Similar presentations

Ads by Google