是线程上的chrono::steady_clock阻塞

Is chrono::steady_clock blocking on threads?

本文关键字:steady clock 阻塞 chrono 线程      更新时间:2023-10-16

当我想生成几个线程来在一定的时间内进行一些计算时,我遇到了一个问题。但是,所用的总时间总是大于每个线程分配的时间之和,而我预计它会超过最大值。我在这里不明白什么?

一些示例代码:

#include <thread>
#include <chrono>
void do_some_wait(int time);
int main() {
  using std::thread;
  thread t1(&do_some_wait, 1);
  thread t2(&do_some_wait, 1);
  thread t3(&do_some_wait, 1);
  t1.join(); t2.join(); t3.join();
}
void do_some_wait(int time) {
  using std::chrono::steady_clock;
  using std::chrono::seconds;
  auto end = steady_clock::now() + seconds(time);
  while (steady_clock::now() < end) { /* some calculations */ }
}

我预计这需要大约1秒的时间来执行。但它需要大约3。

$ clang++ -std=c++11 -stdlib=libc++ -Wall -pedantic thread.cpp -o thread && time ./thread
./thread  2.96s user 0.00s system 295% cpu 1.003 total

time输出中的2.96s user是您使用的CPU时间。如果您在一个至少有三个内核的处理器上运行三个线程,每个线程一秒钟(并且没有来自其他进程的太多竞争),您将使用3秒钟的CPU时间。总时间为1.003秒,这对于1次线程加上开始/结束时的一点开销来说是合理的。

需要1.003秒。您没有注意到输出,这满足了您的期望。