Note that there are some explanatory texts on larger screens.

plurals
  1. POMeasuring efficiency of Mutex and Busy waiting
    text
    copied!<p>The program is to create several threads where each thread increments a shared variable by 10000 using a for loop that increments it by 1 in every iteration. Both mutex lock and spin lock (busy waiting) versions are required. According to what I've learned, mutex version should work faster than spin lock. But what I implemented gave me an opposite answer...</p> <p>This is the inplementation of each thread in the mutex version:</p> <pre><code>void *incr(void *tid) { int i; for(i = 0; i &lt; 10000; i++) { pthread_mutex_lock(&amp;the_mutex); //Grab the lock sharedVar++; //Increment the shared variable pthread_mutex_unlock(&amp;the_mutex); //Release the lock } pthread_exit(0); } </code></pre> <p>And this is the implementation in the spin lock version:</p> <pre><code>void *incr(void *tid) { int i; for(i = 0; i &lt; 10000; i++) { enter_region((int)tid); //Grab the lock sharedVar++; //Increment the shared variable leave_region((int)tid); //Release the lock } pthread_exit(0); } void enter_region(int tid) { interested[tid] = true; //Show this thread is interested turn = tid; //Set flag while(turn == tid &amp;&amp; other_interested(tid)); //Busy waiting } bool other_interested(int tid) //interested[] is initialized to all false { int i; for(i = 0; i &lt; tNumber; i++) if(i != tid) if(interested[i] == true) //There are other threads that are interested return true; return false; } void leave_region(int tid) { interested[tid] = false; //Depart from critical region } </code></pre> <p>I also iterated the process of threads creating and running for hundreds of times to make sure the execution time can be distinguished. For example, if tNumber is 4, and I iterated the program for 1000 times, mutex will take me 2.22 sec, and spin lock will take me 1.35 sec. The difference grows as tNumber increases. Why is this happening? Is my code wrong?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload