60 likes | 78 Views
Pthreads. #include <pthread.h> pthread_t tid ; //thread id. pthread_attr_t attr ; void *sleeping(void *); /* thread routine */ main() { int time = 4; pthread_create (&tid , NULL, sleeping, &time ) ; } void *sleeping((void *) sleep_time) { int *ptr ;
E N D
Pthreads #include <pthread.h> pthread_t tid ; //thread id. pthread_attr_t attr ; void *sleeping(void *); /* thread routine */ main() { int time = 4; pthread_create(&tid, NULL, sleeping,&time) ; } void *sleeping((void *) sleep_time) { int *ptr ; ptr = (int *) sleep_time ; printf(“Getting ready to sleepfor %d secs\n”, *ptr) ; sleep (*ptr) ; printf(“Hello I’m BACK!!\n”) ; }
Pthreads #include <pthread.h> pthread_t tid ; //thread id. pthread_attr_t attr ; void *sleeping(void *); /* thread routine */ main() { int time = 4; pthread_create(&tid, NULL, sleeping, &time) ; } void *sleeping((void *) sleep_time) { int *ptr ; ptr = (int *) sleep_time ; //type cast printf(“Getting ready to sleepfor %d secs\n”, *ptr) ; //dereferencing sleep (*ptr) ; printf(“Hello I’m BACK!!\n”) ; }
Problem: When main exits, all threads are terminated. • Solution: pthread_join(tid, NULL) //this waits for a //particular thread with id tid. • pthread_join(NULL) //waits for any thread.
#include <pthread.h> pthread_t tid ; //thread id. pthread_attr_t attr ; void *sleeping(void *); /* thread routine */ main() { int time = 4; pthread_create(&tid, NULL, sleeping, &time) ; pthread_join(tid, NULL) ; } void *sleeping((void *) sleep_time) { int *ptr ; ptr = (int *) sleep_time ; //type cast printf(“Getting ready to sleepfor %d secs\n”, *ptr) ; //dereferencing sleep (*ptr) ; printf(“Hello I’m BACK!!\n”) ; }
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 ; //shared int june ; //private printf(“thread sleeping for %d secs\n”, *sleep_time) ; tootoo++ ; //will have final value of 20. }