[英]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;
}
cout << sum << endl;
or
cout << sum << "\n";
auto duration = duration_cast<milliseconds>(stopTime - startTime);
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.