Note that there are some explanatory texts on larger screens.

plurals
  1. POCan boost::atomic really improve performance by reducing overhead of sys calls (in mutex/semaphore) in multithreading?
    text
    copied!<p>I am trying to compare the performance of boost::atomic and pthread mutex on Linux:</p> <pre><code> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER ; int g = 0 ; void f() { pthread_mutex_lock(&amp;mutex); ++g; pthread_mutex_unlock(&amp;mutex); return ; } const int threadnum = 100; int main() { boost::threadpool::fifo_pool tp(threadnum); for (int j = 0 ; j &lt; 100 ; ++j) { for (int i = 0 ; i &lt; threadnum ; ++i) tp.schedule(boost::bind(f)); tp.wait(); } std::cout &lt;&lt; g &lt;&lt; std::endl ; return 0 ; } </code></pre> <p>its time:</p> <pre><code> real 0m0.308s user 0m0.176s sys 0m0.324s </code></pre> <p>I also tried boost::atomic: </p> <pre><code> boost::atomic&lt;int&gt; g(0) ; void f() { ++g; return ; } const int threadnum = 100; int main() { boost::threadpool::fifo_pool tp(threadnum); for (int j = 0 ; j &lt; 100 ; ++j) { for (int i = 0 ; i &lt; threadnum ; ++i) tp.schedule(boost::bind(f)); tp.wait() ; } std::cout &lt;&lt; g &lt;&lt; std::endl ; return 0 ; } </code></pre> <p>its time: </p> <pre><code> real 0m0.344s user 0m0.250s sys 0m0.344s </code></pre> <p>I run them many times but the timing results are similar. </p> <p>Can atomic really help avoid overhead of sys calls caused by mutex/semaphore ? </p> <p>Any help will be appreciated. </p> <p>Thanks</p> <p><strong>UPDATE : increase the loop number to 1000000 for</strong> </p> <pre><code> for (int i = 0 ; i &lt; 1000000 ; ++i) { pthread_mutex_lock(&amp;mutex); ++g; pthread_mutex_unlock(&amp;mutex); } </code></pre> <p>similar to boost::atomic .</p> <p>test the time by "time ./app"</p> <p>use boost:atomic: </p> <pre><code>real 0m13.577s user 1m47.606s sys 0m0.041s </code></pre> <p>use pthread mutex:</p> <pre><code>real 0m17.478s user 0m8.623s sys 2m10.632s </code></pre> <p>it seems that boost:atomic is faster because pthread use more time for sys calls.</p> <p>Why user time + sys is larger than real time ? </p> <p>Any comments are welcome !</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