Pthreads include pthread h pthreadt tid thread id




![pthread_t tids[10] ; main() { for (j = 0 ; j < 10 ; pthread_t tids[10] ; main() { for (j = 0 ; j < 10 ;](https://slidetodoc.com/presentation_image_h/263658ade367e6c8811ab0aca284d247/image-5.jpg)

- Slides: 6
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 secsn”, *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 secsn”, *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 secsn”, *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 secsn”, tootoo++ ; //will have final value of 20. } *sleep_time) ;