gpt4 book ai didi

c++ - 带线程的质数

转载 作者:行者123 更新时间:2023-11-28 05:27:17 27 4
gpt4 key购买 nike

我写了一段代码来打印用户写的从头到尾的所有数字。我想用线程来做到这一点。例如,开始是 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);

最佳答案

代码中有很多问题需要修复,素数将从 1 开始,而不是 0,而且你应该开始除以 2 而不是 1 或 0(你不能除以 0),在你得到其余的 0 之后一,它不是素数,它总是以你要计算的数结束(10 % 20 是无意义的)

#include <stdio.h>
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <functional>
#include <fstream>
#include <math.h>

using namespace std;
mutex mtx;

void writePrimesToFile(unsigned int begin, unsigned int end, ofstream& f)
{
for (unsigned int i = begin; i <= end; i++)
{
for (unsigned int j = 2; j < i; j++)
{
if (i % j == 0)
{
break;
}
else if(j + 1 == i)
{
mtx.lock();
f << i << endl;
mtx.unlock();
}
}
}
}

void callWritePrimesMultipleThreads(unsigned int begin, unsigned int end, string filePath, unsigned int N)
{
ofstream myfile(filePath);
clock_t startTimer, stopTimer;

startTimer = clock();

vector<thread> arr;
unsigned int each = end/N;
unsigned int start = begin;
unsigned int finish = start + each - 1;
for (unsigned int i = 0; i < N; i++)
{
arr.emplace_back(writePrimesToFile, start, finish, ref(myfile));
start += each;
finish += each;
}
for (auto& thread : arr)
{
thread.join();
}

stopTimer = clock();
cout << "The time that takes is: " << (double)(stopTimer - startTimer) / CLOCKS_PER_SEC << endl;
}


int main()
{
callWritePrimesMultipleThreads(1, 110, (string)"primes.txt", 10);
return 0;
}

此外,在写入文件时添加了一个互斥量。

关于c++ - 带线程的质数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40287406/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com