1 / 6

Pthreads

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 ;

vcorey
Download Presentation

Pthreads

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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”) ; }

  2. 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”) ; }

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

More Related