Advertisement
Guest User

Untitled

a guest
May 20th, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.30 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6.  
  7. int* thread_counts;
  8. pthread_t* threads;
  9. int tcount = 0;
  10.  
  11. pthread_mutex_t mutex;
  12.  
  13. void* threadAction(void* arg) {
  14.   int tid;
  15.   pthread_mutex_lock(&mutex);
  16.   tid=tcount;
  17.   tcount++;
  18.   pthread_mutex_unlock(&mutex);
  19.  
  20.   while (1) {
  21.     pthread_mutex_lock(&mutex);
  22.     thread_counts[tid]++;
  23.     pthread_mutex_unlock(&mutex);
  24.   }
  25. }
  26.  
  27. int main(int argc, char *argv[]) {
  28.   int error, n_threads;
  29.   if (argc < 2) {
  30.     printf("USAGE: %s NUM_THREADS\n", argv[0]);
  31.     return 1;
  32.   }
  33.   n_threads = atoi(argv[1]);
  34.   thread_counts = malloc(sizeof(int) * n_threads);
  35.   threads = malloc(sizeof(int) * n_threads);
  36.  
  37.   if (pthread_mutex_init(&mutex, NULL) != 0) {
  38.     printf("Could not initialize mutex");
  39.     return 1;
  40.   }
  41.  
  42.   for (int i=0; i < n_threads; i++) {
  43.     error = pthread_create(&(threads[i]), NULL, &threadAction, NULL);
  44.     if (error != 0) {
  45.       printf("Error creating thread %u", i);
  46.       return 1;
  47.     }
  48.   }
  49.   printf("Set everything up, sleeping now...\n");
  50.   sleep(1);
  51.  
  52.   for (int i=0; i < n_threads; i++) {
  53.     thread_counts[i] = 0;
  54.   }
  55.  
  56.   sleep(3);
  57.   for (int i=0; i < n_threads; i++) {
  58.     printf("Counter %u has value %u\n", i, thread_counts[i]);
  59.   }
  60.   return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement