小编Sta*_*Lee的帖子

为什么添加线程不能带来进一步的性能提升

我正在学习 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)

c++ concurrency multithreading stdatomic

2
推荐指数
1
解决办法
134
查看次数

标签 统计

c++ ×1

concurrency ×1

multithreading ×1

stdatomic ×1