我在玩 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慢?
发布评论