我一直在尝试对我用 C++ 编写的素数生成器的多线程进行一些研究,我发现我想要做的就是所谓的“并行处理”。在过去的大约 45 分钟里,我一直在研究这个问题,但我似乎无法弄清楚。
我要执行此操作的代码大约有 95 行,这太长了,无法在此处发布,但这是基本概念:
unsigned long long i, total;
for(i;true;i++){
total = total + i;
cout << "Your new total is " << total << endl;
}
有什么办法可以将它流式传输到 2 个处理器,以便它们一起工作而不是竞争?如果是这样,我将如何编码?我对 C++ 有点熟悉,但还有很多我不知道的地方,因此非常感谢您提供深入的回答。
编辑:第一次使用错误的算法。我觉得这就是。
编辑 2:由于很多答案都说这取决于我的算法,所以我将发布我的代码,因为它只有 95 行。
/*Generic GPL stuff, coded by me */
#include <iostream>
#include <list>
#include <fstream>
using namespace std;
int main(){
//Declare some variables and what not.
unsigned long long count = 0, misc = 0, length = 0, limit = 0;
list <long long> primes;
ifstream inFile;
ofstream outFile;
cout << "Initializing starting values based on your existing file of generated prime numbers.\n";
//Now let's get our starting values;
inFile.open("/home/user/Desktop/primes.txt");
//First, we need to find the prime generator thus far
for(unsigned long long x=0;inFile.good();x++){
inFile >> count;
if(!(bool)(x%100000000) && x!=0){
misc = x/100000000;
cout << misc << "00000000 primes read so far...\n";
}
}
inFile.close();
cout << "Highest generated prime found.\n";
//Now, as much as I hate to say it, we need to parse part of the file again now that we have the largest prime.
inFile.open("/media/ssd/primes_src.txt");
for(length; limit < count; length++){
inFile >> misc;
}
inFile.close();
limit = misc * misc;
cout << "Initialization complete. Now generating primes.\n";
//Loop time
l:
//We're just going to flat-out skip even numbers
count++;
count++;
//This checks to see if the number it's trying to test is beyond the current limit of accuracy.
if(count >= limit){
// Now if we are, we have 1 more possible prime factor
length++;
inFile.open("/media/ssd/primes_src.txt");
for(unsigned long long x=0; x < length; x++){
inFile >> misc;
}
inFile.close();
limit = misc * misc;
}
inFile.open("/media/ssd/primes_src.txt");
inFile >> misc; //We don't care about 2
for(unsigned long long x=1; x < length; x++){
inFile >> misc;
if(!(bool)(count%misc)){
inFile.close();
goto l;
}
}
inFile.close();
outFile.open("/home/user/Desktop/primes.txt", ios::out | ios::app);
//Now if we haven't been "goto"d, we add it to the file.
outFile << count << endl;
outFile.close();
goto l;
return 0;
}
/home/user/Desktop/primes.txt 是我保存所有生成的素数的文件。
/media/ssd/primes_src.txt 是我的文件,其中包含高达 2^32 的所有素数加上 1 个素数,以供良好测量。