Advertisement
AlexMatveev

pthreads

Nov 30th, 2011
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 KB | None | 0 0
  1. #include <sys/times.h>
  2. #include <time.h>
  3. #include <stdio.h>
  4. #include <pthread.h>
  5.  
  6. long long int tmsBegin1,tmsEnd1,tmsBegin2,tmsEnd2,tmsBegin3,tmsEnd3;
  7.  
  8. int array[100];
  9.  
  10. void *heavy_loop(void *param) {
  11.   int   index = *((int*)param);
  12.   int   i;
  13.   for (i = 0; i < 100000000; i++)
  14.     array[index]+=3;
  15. }
  16.  
  17. int main(int argc, char *argv[]) {
  18.   int       first_elem  = 0;
  19.   int       bad_elem    = 1;
  20.   int       good_elem   = 32;
  21.   long long time1;
  22.   long long time2;
  23.   long long time3;
  24.   pthread_t     thread_1;
  25.   pthread_t     thread_2;
  26.   pthread_t     thread_3;
  27.  
  28.   tmsBegin3 = clock();
  29.   heavy_loop((void*)&first_elem);
  30.   heavy_loop((void*)&bad_elem);
  31.   tmsEnd3 = clock();
  32.  
  33.   tmsBegin1 = clock();
  34.   pthread_create(&thread_1, NULL, heavy_loop, (void*)&first_elem);
  35.   pthread_create(&thread_2, NULL, heavy_loop, (void*)&bad_elem);
  36.   pthread_join(thread_1, NULL);
  37.   pthread_join(thread_2, NULL);
  38.   tmsEnd1 = clock();
  39.  
  40.   tmsBegin2 = clock();
  41.   pthread_create(&thread_1, NULL, heavy_loop, (void*)&first_elem);
  42.   pthread_create(&thread_3, NULL, heavy_loop, (void*)&good_elem);
  43.   pthread_join(thread_1, NULL);
  44.   pthread_join(thread_3, NULL);
  45.   tmsEnd2 = clock();
  46.    
  47.   printf("%d %d %d\n", array[first_elem],array[bad_elem],array[good_elem]);
  48.   time1 = (tmsEnd1-tmsBegin1)*1000/CLOCKS_PER_SEC;
  49.   time2 = (tmsEnd2-tmsBegin2)*1000/CLOCKS_PER_SEC;
  50.   time3 = (tmsEnd3-tmsBegin3)*1000/CLOCKS_PER_SEC;
  51.   printf("%lld ms\n", time1);
  52.   printf("%lld ms\n", time2);
  53.   printf("%lld ms\n", time3);
  54.  
  55.   return 0;
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement