Advertisement
Guest User

pthread_mutex simple example

a guest
Feb 24th, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.08 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3.  
  4. const long kSize = 1e7L;
  5.  
  6. long ctr = 0;
  7. pthread_mutex_t mtx;
  8. void *func1(void *a) {
  9.     for (long i = 0; i < kSize; ++i) {
  10.         pthread_mutex_lock(&mtx);
  11.         ++ctr;
  12.         pthread_mutex_unlock(&mtx);
  13.     }
  14.     return NULL;
  15. }
  16.  
  17. void *func2(void *a) {
  18.     for (long i = 0; i < kSize; ++i) {
  19.        pthread_mutex_lock(&mtx);
  20.        --ctr;
  21.        pthread_mutex_unlock(&mtx);
  22.     }
  23.     return NULL;
  24. }
  25.  
  26. int main(void) {
  27.     clock_t start = clock();
  28.     if (pthread_mutex_init(&mtx, PTHREAD_MUTEX_NORMAL) != 0) {
  29.         fprintf(stderr, "pthread_mutex_init(): Error.\n");
  30.         return -1;
  31.     }
  32.     pthread_t th1, th2;
  33.     if (pthread_create(&th1, NULL, func1, NULL) != 0 ||
  34.         pthread_create(&th2, NULL, func2, NULL) != 0) {
  35.         fprintf(stderr, "pthread_create(): Error.\n");
  36.         return -1;
  37.     }
  38.  
  39.     pthread_join(th1, NULL);
  40.     pthread_join(th2, NULL);
  41.     pthread_mutex_destroy(&mtx);
  42.    
  43.     printf("Counter: %ld \t CPU time: %ld ms\n",
  44.             ctr, (clock() - start) * 1000L / CLOCKS_PER_SEC);
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement