Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 25th, 2012  |  syntax: None  |  size: 1.42 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Measuring efficiency of Mutex and Busy waiting
  2. void *incr(void *tid)
  3. {
  4.     int i;
  5.     for(i = 0; i < 10000; i++)
  6.     {
  7.         pthread_mutex_lock(&the_mutex);     //Grab the lock
  8.         sharedVar++;    //Increment the shared variable
  9.         pthread_mutex_unlock(&the_mutex);   //Release the lock
  10.     }
  11.     pthread_exit(0);
  12. }
  13.        
  14. void *incr(void *tid)
  15. {
  16.     int i;
  17.     for(i = 0; i < 10000; i++)
  18.     {
  19.         enter_region((int)tid);  //Grab the lock
  20.         sharedVar++;        //Increment the shared variable
  21.         leave_region((int)tid);  //Release the lock
  22.     }
  23.     pthread_exit(0);
  24. }
  25. void enter_region(int tid)
  26. {
  27.     interested[tid] = true;     //Show this thread is interested
  28.     turn = tid;     //Set flag
  29.     while(turn == tid && other_interested(tid));    //Busy waiting
  30. }
  31. bool other_interested(int tid)    //interested[] is initialized to all false
  32. {
  33.     int i;
  34.     for(i = 0; i < tNumber; i++)
  35.         if(i != tid)
  36.             if(interested[i] == true)   //There are other threads that are interested
  37.                 return true;
  38.     return false;
  39. }
  40. void leave_region(int tid)
  41. {
  42.     interested[tid] = false;    //Depart from critical region
  43. }
  44.        
  45. if (check[sharedVar]) cout << "ERROR" << endl;
  46. else check[sharedVar++] = true;
  47.        
  48. interested[tid] = true;     //Show this thread is interested
  49. turn = tid;     //Set flag
  50. while(turn == tid && other_interested(tid));
  51.        
  52. while( compare_and_swap_atomic(myid,id_meaning_it_is_free) == false);