Pthreads #include pthread_t tid ; //thread id. pthread_attr_t attr ; void *sleeping(void *); /* thread routine */ main() { int time = 2 ; pthread_create(&tid, NULL, sleeping, &time) ; } void *sleeping(int * sleep_time) { printf(“thread sleeping for %d secs\n”, *sleep_time) ; }
Pthreads Problem: When main exits the process exits. main() { int time = 2 ; pthread_create(&tid, NULL, sleeping, &time) ; pthread_join(tid, void NULL); } void *sleeping(int * sleep_time) { printf(“thread sleeping for %d secs\n”, *sleep_time) ; }
pthread_t tids[10] ; main() { for (j = 0 ; j < 10 ; j++) pthread_create(&tids[i], NULL, sleeping, &time) ; for(j = 0 ; j < 10 ; j++) pthread_join(tid[i], NULL) ; }
All theads share: global variables file descriptors static variables within creating function. Local variables are private to each thread. void *sleeping(int * sleep_time) { static int tootoo = 10 ; printf(“thread sleeping for %d secs\n”, *sleep_time) ; tootoo++ ; //will have final value of 20. }
Synchronization Constructs mutex and condition variables: Main() { pthread_mutex_t my_mute ; //initialize pthread_mutex_init(&my_mute, NULL) ; pthread_mutex_lock(&my_mute);//blocks caller till mutex unlocked // by owner -critical code pthread_mutex_unlock(&my_mute);
You can also test a mutex to see if it is available pthread_mutex_trylock(&my_mute) ; If multiple threads blocked on mutex, one will be chosen Based on the scheduling algorithm.
Condition variable allows threads to wait on some event and resume when the event has occurred. Condition variable associated with a mutex! Thread must acquire mutex before calling pthread_cond_wait(). pthread_mutex_t my_mute ; pthread_cond_t condalisa ; pthread_mutex_init(&mymute) ; thread_cond_init(&condalisa) ;
pthread_mutex_lock(&my_mute) ; pthread_cond_wait(&condalisa, &my_mute); This call to wait atomically checks the condition and blocks (if necessary). If the thread blocks, the mutex is automatically released. Woken up with call to pthread_cond_signal ; pthread_cond_signal(&condalisa) ; //wakes up one //thread. pthread_cond_broadcast (&condalisa) ; //wakes up all threads