了解为什么std :: mutex在macOS上花费的时间比Linux多吗?

时间:2018-07-23 06:22:48

标签: linux multithreading macos concurrency

我想了解为什么此代码在MacO中比在Linux中更慢

以下是我的代码:

#include <iostream>
#include <chrono>
#include <mutex>
#include <thread>

using std::cout;
using std::endl;

#define THREAD_NUM 4
#define THREAD_OP_COUNT 1000000

std::mutex m_total_lock;
uint64_t m_total;

void test_mutex()
{
  for (int i = 0; i < THREAD_OP_COUNT; i++) {
    m_total_lock.lock();
    m_total++;
    m_total_lock.unlock();
  }
}

int main(int argc, char *argv[])
{
  std::chrono::time_point<std::chrono::system_clock> start, end;
  start = std::chrono::system_clock::now();
  std::thread t[THREAD_NUM];

  for (int i = 0; i < THREAD_NUM; i++)
    t[i] = std::thread(test_mutex);

  for (int i = 0; i < THREAD_NUM; i++)
    t[i].join();

  end = std::chrono::system_clock::now();
  std::chrono::duration<double> elapsed_seconds = end - start;
  cout << elapsed_seconds.count() << endl;
  cout << m_total << endl;

  return 0;
}

运行结果:

macOS

[Zealoussnow  C++11]$ time ./demo

15.1557

4000000

./demo  4.03s user 13.66s system 116% cpu 15.160 total

Linux

Linux zealoussnow 3.10.0-693.5.2.el7.x86_64 #1 SMP Fri Oct 20 20:32:50 UTC 

2017 x86_64 x86_64 x86_64 GNU/Linux

[Zealoussnow] $ time ./demo

0.555695

4000000

./demo  0.56s user 0.95s system 269% cpu 0.560 total

因此,我对此问题感到非常困惑,我尝试在macOS中添加pthread_setconcurrency,但没有任何效果。

您能解释一下区别吗?

0 个答案:

没有答案