当我想生成几个线程在设定的时间内进行一些计算时,我遇到了一个问题。但是经过的总时间总是大于每个线程分配时间的总和,而我预计它会超过最大值。我在这里不明白什么?
一些示例代码:
#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