hqt

pthread example

hqt
Aug 12th, 2012
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.94 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<math.h>
  3. #include<pthread.h>
  4. #include <unistd.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <errno.h>
  8.  
  9. volatile int beers = 2000000;
  10. pthread_mutex_t p_thread_lock = PTHREAD_MUTEX_INITIALIZER;
  11.  
  12. struct {
  13.     char a;
  14.     char b;
  15.     char c;
  16.     char d;
  17.     char e;
  18. }data;
  19. void* drink(void*a){
  20.     int i;
  21.     pthread_mutex_lock(&p_thread_lock);
  22.     for(i=0; i<100000; i++){
  23.         beers--;
  24.     }
  25.     pthread_mutex_unlock(&p_thread_lock);
  26.    
  27.     long thread_no = (long)a;
  28.     return (void*)(thread_no +1);
  29. }
  30.  
  31. int main(){
  32.     pthread_t threads[20];
  33.     int t = 0;
  34.     for(t=0; t<20; t++){
  35.         pthread_create(&threads[t],NULL,drink,(void*)t);
  36.     }
  37.    
  38.     void* result;
  39.     for(t=0; t<20; t++){
  40.         pthread_join(threads[t], &result);
  41.         printf("Thread %ld returned %ld\n",t,(long)result);
  42.     }
  43.    
  44.     printf("There are now %i bottles of beer on the wall\n", beers);
  45.    
  46. }
Advertisement
Add Comment
Please, Sign In to add comment