Advertisement
Guest User

Untitled

a guest
Mar 29th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. //In this assignment, we use multiple threads to calculate the sum
  2. // 1*1 + 2*2 + 3*3 + 4*4 + ... + n*n
  3. // Note we should know from CSE2500 that this sum is
  4. // n*(n+1)*(2*n+1)/6
  5. // We a n value, we will create 2*n threads to do the calculation
  6. // Before you change the code, read the code and run the code and see what
  7. // happens. Do we always get the result sum?
  8. // Read the code carefully and make changes to the code.
  9. // Use mutex to ensure we always get the right sum.
  10.  
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <assert.h>
  14. #include <pthread.h>
  15. #include <unistd.h>
  16. #define MAX 1000
  17.  
  18.  
  19. int n;
  20. unsigned long sum = 0;
  21. pthread_mutex_t mutex;
  22.  
  23. void* calculate(void* threadarg)
  24. {
  25.  
  26. //fill in one line of code blew
  27. pthread_mutex_lock(&mutex);
  28. if(n > 0)
  29. {
  30. sum += n*n;
  31. //do not delete the following line of code
  32. //this line helps us to see wrong results
  33. sleep(0);
  34. n--;
  35. }
  36. //fill in one line of code below
  37. pthread_mutex_unlock(&mutex);
  38. pthread_exit(NULL);
  39. }
  40.  
  41. int main(int argc, char *argv[])
  42. {
  43.  
  44. if(argc!=2)
  45. {
  46. printf("Usage: %s n (1 - 500)\n", argv[0]);
  47. return -1;
  48. }
  49.  
  50. n = atoi(argv[1]);
  51. assert(n >= 1 && n <= MAX/2);
  52.  
  53. //save n to k for later use
  54. int k = n;
  55. int m = 2*n;
  56.  
  57. //fill in one line of code below
  58. pthread_mutex_init(&mutex, NULL);
  59. pthread_t threads[MAX];
  60. int rc, t;
  61. for( t=0; t<m; t++ ) {
  62. //Since we do not need to pass any arguments to the thread, we pass a NULL
  63. rc = pthread_create(&threads[t], NULL, calculate, NULL);
  64. if (rc) {
  65. printf("ERROR; return code from pthread_create() is %d\n", rc);
  66. exit(-1);
  67. }
  68. }
  69.  
  70. for( t=0; t<m; t++ )
  71. {
  72. rc = pthread_join( threads[t], NULL );
  73. if( rc ){
  74. printf("ERROR; return code from pthread_join() is %d\n", rc);
  75. exit(-1);
  76. }
  77. }
  78. //fill in one line of code below
  79. pthread_mutex_destroy(&mutex);
  80. unsigned long correct_sum = k*(k+1)*(2*k+1)/6;
  81. printf("thread sum : %ld correct sum : %ld\n", sum, correct_sum);
  82. return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement