multi-threaded programming with posix threads cse331 operating systems design

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

Upload: domenic-alexander

Post on 03-Jan-2016

235 views

Category:

Documents


3 download

TRANSCRIPT

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

Multi-threaded Programming with

POSIX Threads

CSE331Operating Systems Design

Page 2: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

Processes vs Threads

Stack

Data

Text

Process1

Stack

Data

Text

Process2

Stack2

Data

Text

Thread1

Stack1

Thread2

Page 3: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

Some Terms

• Thread Safe• Reentrant• Multi-threaded• POSIX

Page 4: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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.

Page 5: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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

Page 6: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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

Page 7: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

#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

Page 8: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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.

Page 9: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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.

Page 10: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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 thread1pthread_t t2, // ID of thread2

);

Description: Return zero if equal.Non-zero if not.

Page 11: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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.

Page 12: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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

}

Page 13: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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 Threads1) 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.

Page 14: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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

Page 15: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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.

Page 16: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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

Page 17: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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

Page 18: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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

Page 19: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

Mutual ExclusionSimplest 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

Page 20: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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

Page 21: Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

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();}