繁体   English   中英

C++ 中的线程中出现意外的 output

[英]Unexpected output in threads in C++

我是线程新手,我写了一个简单的线程程序来看看它在 C++ 中是如何工作的。

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
using namespace std::chrono;

void funcSum(long long int start, long long end)
{
    long long int sum = 0;
    for(auto i = start; i <= end; ++i)
    {
        sum += i;
    }
    cout << sum;
}
int main()
{
    auto startTime = high_resolution_clock::now();
    long long int start = 0, end = 90000;
    thread t1(funcSum, start, end);
    t1.join();
    funcSum(start, end);
    auto stopTime = high_resolution_clock::now();
    auto duration = duration_cast<seconds>(startTime - stopTime);
    cout << "\n" << duration.count() << " Seconds\n";
    return 0;
}

上面的代码产生一些随机 output: 40500450004050045000 0 秒

这段代码有什么问题? 为什么我得到一个随机的垃圾号码? 我希望它只打印从 0 到 90000 的数字总和。

请注意,您正在funcSum两次。 一旦它在一个新线程中运行,然后在线程完成后再次运行(当join()完成时)。

funcSum中,您忘记添加新行。 两次执行都按预期打印4050045000但结果没有分开,所以它可能看起来像垃圾。

这应该可以解决问题:

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
using namespace std::chrono;

void funcSum(long long int start, long long end)
{
    long long int sum = 0;
    for(auto i = start; i <= end; ++i)
    {
        sum += i;
    }
    // add new line to make output more readable
    cout << "Calculated sum: " << sum << "\n";
}
int main()
{
    auto startTime = high_resolution_clock::now();
    long long int start = 0, end = 90000;
    thread t1(funcSum, start, end);
    t1.join();
    // no need to call funcSum again, it will be called in t1 anyways
    auto stopTime = high_resolution_clock::now();
    auto duration = duration_cast<seconds>(startTime - stopTime);
    cout << "Duration: " << duration.count() << " Seconds\n";
    return 0;
}
  1. 您的 function output 是:4050045000 并在代码中调用了两次。 因为你在使用“cout”时没有使用“std::endl”或“\n”,所以两个结果都在同一行。 所以首先修改function:
cout << sum << endl;

or

cout << sum << "\n";
  1. 对于比消极有意义的积极结果:
 auto duration = duration_cast<milliseconds>(stopTime - startTime);
  1. 对于计算线程时间,您应该在启动它之前花费一些时间,并在 thread.join() 之后停止计时。 由于这种情况下的线程时间很少,使用“秒”是不合适的,最好使用“毫秒”。
    long long int start = 0, end = 90000;
    
    auto startTime =  high_resolution_clock::now();
    thread t1(funcSum, start, end);
    t1.join();
    auto stopTime = high_resolution_clock::now();
    
    auto duration = duration_cast<milliseconds>(stopTime - startTime);
    cout << "Duration: " << std::chrono::milliseconds(duration).count() << " Milliseconds\n";
    cin.get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM