2线程比1慢? [英] 2 threads slower than 1?

查看:153
本文介绍了2线程比1慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩 std :: thread ,并弹出一些怪异的:

I was playing around with std::thread and something weird popped up:

#include <thread>

int k = 0;

int main() {
    std::thread t1([]() { while (k < 1000000000) { k = k + 1; }});
    std::thread t2([]() { while (k < 1000000000) { k = k + 1; }});

    t1.join();
    t2.join();

    return 0;
}

在没有使用clang ++进行优化的情况下编译上述代码时, :

When compiling the above code with no optimizations using clang++, I got the following benchmarks:

real 0m2.377s  
user 0m4.688s  
sys  0m0.005s

然后我将代码更改为以下内容:(现在只使用1个线程)

I then changed my code to the following: (Now using only 1 thread)

#include <thread>

int k = 0;

int main() {
    std::thread t1([]() { while (k < 1000000000) { k = k + 1; }});

    t1.join();

    return 0;
}

这些是新的基准:

real 0m2.304s
user 0m2.298s
sys  0m0.003s

为什么使用2个线程的代码比使用1的代码慢?

推荐答案

你有两个线程争夺同一个变量, k 。所以你花费时间在处理器说处理器1:嘿,你知道什么价值 k 有?处理器2:当然,这里你去!,乒乓每来几个更新来回。由于 k 不是原子的,因此也不能保证thread2不会写入一个旧值 k 因此下一次线程1读取值时,它跳回1,2,10或100步,并且必须重复 - 在理论上,这可能导致每个完成没有循环,但是这将需要相当多的的坏运气。

You have two threads fighting over the same variable, k. So you are spending time where the processors say "Processor 1: Hey, do you know what value k has? Processor 2: Sure, here you go!", ping-ponging back and forth every few updates. Since k isn't atomic, there's also no guarantee that thread2 doesn't write an "old" value of k so that next time thread 1 reads the value, it jumps back 1, 2, 10 or 100 steps, and has to do it over again - in theory that could lead to neither of the loops every finishing, but that would require quite a bit of bad luck.

这篇关于2线程比1慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆