【发布时间】:2016-10-27 14:34:10
【问题描述】:
我写了一个代码来打印用户从头到尾写的所有数字。我想用线程来做到这一点。例如,开始是 1,结束是 100。我要求用户输入一个 N 数字,这是程序创建的线程数。例如,如果他输入 10,程序将创建 10 个线程。第一个线程将打印从 1 到 10 的素数。第二个线程将打印从 10 到 20 的素数。第三个线程将打印从 20 到 30 的素数……
但是我有一个问题。事实上,我的程序在文件中打印了许多不是素数的数字,而且我经常在代码中多次打印相同的数字。
这是我的代码:
void writePrimesToFile(int begin, int end, ofstream& file)
{
for (int i = begin; i <= end; i++)
{
for (int j = begin; j < end / 2; j++)
{
if (i % j != 0)
{
file << i << endl;
}
}
}
}
void callWritePrimesMultipleThreads(int begin, int end, string filePath, int N)
{
ofstream myfile(filePath);
clock_t startTimer, stopTimer;
startTimer = clock();
vector<thread> arr;
for (int i = 0; i < N; i++)
{
int start = begin;
int finish = N;
arr.emplace_back(writePrimesToFile, start, finish, ref(myfile));
start = finish;
finish += N;
}
for (auto& thread : arr)
{
thread.join();
}
stopTimer = clock();
cout << "The time that takes is: " << (double)(stopTimer - startTimer) / CLOCKS_PER_SEC << endl;
}
主代码:
callWritePrimesMultipleThreads(1, 100, "primes2.txt", 10);
【问题讨论】:
-
您在使用调试器时观察到了什么?
-
if (i % j != 0)看起来不对 -
@AlgirdasPreidžius 任何可以帮助我解决错误的东西。
-
for (int j = begin; j < end / 2; j++)是错误的。你应该从j=2开始 -
@RonyCohen 等等,什么?这不是我的问题的答案。您甚至尝试过使用调试器吗?您在使用时观察到了什么?由于调试器是第一个使用的工具,因此当您的代码未按预期运行时。简而言之:您的主要检测算法有缺陷,问题与线程无关。
标签: c++ multithreading