Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.94 KB | None | 0 0
  1. /*
  2. Note To compile thread-based programs you must use the -pthread compiler option.
  3. This ensures linking with the libpthread library and with the thread-safe
  4. functions of the C library.
  5.  
  6. IMP. Follow an incremental code development approach. If you write all the code
  7. in a single go and only then compile it, you risk spending the following 15
  8. minutes eliminating the compilation errors and the remaining class debugging it.
  9. Instead, you should add code step by step, compiling it and testing it, after
  10. each step.
  11.  
  12. In this problem you will write a very simple multi-threaded program that
  13. increments a shared counter.
  14. The program's main thread creates 3 other threads.
  15.  
  16. Each ot these 3 threads shall increment a shared counter (long int) a number of
  17. times, specified as a command line argument to the program.
  18.  
  19. The main thread shall wait for the termination of the other 3 threads, and then
  20. shall print the final value of the counter.
  21.  
  22. Compile your program and run it several times. Explain the observed results.
  23. */
  24. #include <stdio.h>
  25. #include <pthread.h>
  26. #include <stdlib.h>
  27.  
  28.  
  29. typedef struct __myarg_t{
  30.   long int counter;
  31.   long int num_increments;
  32. } myarg_t;
  33.  
  34. void *increment(void *args){
  35.   myarg_t *res = (myarg_t *) args;
  36.  
  37.   for(int i = 0; i < res->num_increments; i++){
  38.     ++res->counter;
  39.   }
  40.   return (void *) res->counter;
  41. }
  42.  
  43. int main(int argc, char* argv[]){
  44.   if(argc == 2){
  45.     myarg_t args;
  46.  
  47.     args.counter = 0;
  48.     args.num_increments = atoi(argv[1]);
  49.  
  50.     long int tcounter[3];
  51.    
  52.     pthread_t t[3];
  53.  
  54.     for(int i = 0; i < 3; i++){
  55.     tcounter[i] = pthread_create(&t[i], NULL, increment, &args);
  56.     }
  57.    
  58.     for(int i = 0; i < 3; i++){
  59.         pthread_join(t[i], (void **) &tcounter[i]);
  60.     printf("Thread %d has counter = %ld\n", i+1, tcounter[i]);
  61.     }
  62.      
  63.     printf("%ld\n", args.counter);
  64.  
  65.   }
  66.   else if (argc < 2) printf("Few Arguments!\n");
  67.   else printf("Too Many Arguments!\n");
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement