boost :: atomic可以通过减少多线程中sys调用(在互斥/信号量中)的开销来真正提高性能吗?

use*_*107 3 c++ multithreading boost pthreads atomic

我试图在Linux上比较boost :: atomic和pthread mutex的性能:

 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER ;
 int g = 0 ;

 void f()
 {

    pthread_mutex_lock(&mutex);
    ++g;
    pthread_mutex_unlock(&mutex);
    return ;
 }
 const int threadnum = 100;
 int main()  
 {
    boost::threadpool::fifo_pool tp(threadnum);
    for (int j = 0 ; j < 100 ; ++j)
    {
            for (int i = 0 ; i < threadnum ; ++i)
                    tp.schedule(boost::bind(f));
            tp.wait();
    }
    std::cout << g << std::endl ;
    return 0 ; 
 }
Run Code Online (Sandbox Code Playgroud)

是时候了:

 real    0m0.308s
 user    0m0.176s
 sys     0m0.324s
Run Code Online (Sandbox Code Playgroud)

我也试过boost :: atomic:

 boost::atomic<int> g(0) ;

 void f()
 {

      ++g;
    return ;
  }
  const int threadnum = 100;
  int main()
  {
    boost::threadpool::fifo_pool tp(threadnum);
    for (int j = 0 ; j < 100 ; ++j)
    {
            for (int i = 0 ; i < threadnum ; ++i)
                    tp.schedule(boost::bind(f));
            tp.wait() ;
    }
    std::cout << g << std::endl ;
    return 0 ;
   }
Run Code Online (Sandbox Code Playgroud)

是时候了:

 real    0m0.344s
 user    0m0.250s
 sys     0m0.344s
Run Code Online (Sandbox Code Playgroud)

我运行了很多次,但时间结果相似.

原子能真的有助于避免互斥/信号量导致的sys调用开销吗?

任何帮助将不胜感激.

谢谢

更新:将循环次数增加到1000000

    for (int i = 0 ; i < 1000000 ; ++i)
    {
            pthread_mutex_lock(&mutex);
            ++g;
            pthread_mutex_unlock(&mutex);
    }
Run Code Online (Sandbox Code Playgroud)

类似于boost :: atomic.

用"time ./app"测试时间

使用boost:atomic:

real    0m13.577s
user    1m47.606s
sys     0m0.041s
Run Code Online (Sandbox Code Playgroud)

使用pthread互斥量:

real    0m17.478s
user    0m8.623s
sys     2m10.632s
Run Code Online (Sandbox Code Playgroud)

似乎boost:atomic更快,因为pthread使用更多时间进行sys调用.

为什么用户时间+ sys大于实时?

欢迎任何评论!

Fré*_*oni 5

我猜你没有正确测量原子与互斥的时间.相反,您正在测量增强线程池管理所产生的开销:设置新任务f()比执行任务本身需要更多时间.

我建议你在f()中添加另一个循环来获得这样的东西(对于原子版本做同样的事情)

 void f()
 {
    for(int i = 0  ; i < 10000 ; i++) {
      pthread_mutex_lock(&mutex);
      ++g;
      pthread_mutex_unlock(&mutex);
    }
    return ;
 }
Run Code Online (Sandbox Code Playgroud)

如果发生变化,请发布分数,我有兴趣看看差异!