2线程比1慢?

编程入门 行业动态 更新时间:2024-10-10 12:19:43
本文介绍了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慢?

本文发布于:2023-11-23 12:56:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621524.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!