Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pthreads void *sleeping(void *); /* thread routine */

Similar presentations


Presentation on theme: "Pthreads void *sleeping(void *); /* thread routine */"— Presentation transcript:

1 Pthreads void *sleeping(void *); /* thread routine */
#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”) ;

2 Pthreads void *sleeping(void *); /* thread routine */
#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”) ;

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

4 #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”) ;

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

6 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. }


Download ppt "Pthreads void *sleeping(void *); /* thread routine */"

Similar presentations


Ads by Google