我正在学习 C++ 多线程编程。我的测试程序很简单,功能就是统计一个原子变量从0到10000000(高一点也没关系)。我不明白为什么当我将线程数从8设置为16后,执行时间反而增加了一些而不是大幅下降。
std::atomic<int> atomicCounter{0};
void addcount(int threadId) {
while(atomicCounter.load() < 10000000) {
atomicCounter.fetch_add(1);
}
}
void test() {
const int maxNumThreads = 8;
// Time::now() is to get the timestamp accurate to ns
auto s_ts = Time::now();
std::vector<std::thread> threads;
for (int i = 0; i < maxNumThreads; i++) {
threads.emplace_back([&]() {
addcount(i);
});
}
// join the threads
for (auto& thread : threads) {
thread.join();
}
threads.clear();
auto e_ts = Time::now();
LOG(INFO) << "Executing time : " << (e_ts …Run Code Online (Sandbox Code Playgroud)