Advertisement
Guest User

Untitled

a guest
May 5th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.89 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3.  
  4. #define NTHREADS 10
  5. void *thread_function(void *);
  6. pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
  7. int  counter = 0;
  8.  
  9. main()
  10. {
  11.  
  12.    pthread_t thread_id[NTHREADS];
  13.    int i, j;
  14.  
  15.    for(i=0; i < NTHREADS; i++)
  16.    {
  17.       pthread_create( &thread_id[i], NULL, thread_function, NULL );
  18.    }
  19.  
  20.    for(j=0; j < NTHREADS; j++)
  21.    {
  22.       pthread_join( thread_id[j], NULL);
  23.    }
  24.  
  25.    /* Now that all threads are complete I can print the final result.     */
  26.    /* Without the join I could be printing a value before all the threads */
  27.    /* have been completed.                                                */
  28.  
  29.    printf("Final counter value: %d\n", counter);
  30. }
  31.  
  32. void *thread_function(void *dummyPtr)
  33. {
  34.    printf("Thread number %ld\n", pthread_self());
  35.    pthread_mutex_lock( &mutex1 );
  36.    counter++;
  37.    pthread_mutex_unlock( &mutex1 );
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement