我已经编写了一个代码,在最终产品中假设接收一个文件并使用多线程来帮助定位所有主要值。不幸的是,这没有按计划工作,我的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <pthread.h>
#define maxIntArraySize 10000
struct sum_struct{
long long answer;
int * takeNum;
};
/// primality test, if n is prime, return 1, else return 0
int isPrime(int64_t n)
{
if( n <= 1) return 0; // small numbers are not primes
if( n <= 3) return 1; // 2 and 3 are prime
if( n % 2 == 0 || n % 3 == 0) return 0; // multiples of 2 and 3 are not primes
int64_t i = 5;
int64_t max = sqrt(n);
while( i <= max) {
if (n % i == 0 || n % (i+2) == 0) return 0;
i += 6;
}
return 1;
}
//Thread function to generate the # of primes in said thread
void* sum_runner(void* arg)
{
struct sum_struct *arg_struct = (struct sum_struct*) arg;
long long sum = 0;
int countTakeNum = sizeof(arg_struct->takeNum)/sizeof(int);
for(int p = 0; p <= countTakeNum; p++) {
if( isPrime(arg_struct->takeNum[p]) == 1) {sum = sum + 1;}
}
arg_struct->answer = sum;
pthread_exit(0);
}
// Takes out the first requires values
int *takeOut(int * list, int div)
{
static int r[100];
for (int h = 0; h < div; h++){
r[h] = list[h];
}
return r;
}
// Main Function
int main( int argc, char ** argv)
{
int nThreads = atoi(argv[1]);
int listOfNums[maxIntArraySize];
int currentSize = 0;
int listCounter = 0;
/// count the primes
printf("Counting primes using %d thread%s.\n", nThreads, nThreads == 1 ? "s" : "");
int64_t count = 0;
while( 1) {
int64_t num;
if( 1 != scanf("%ld", & num)) break;
//printf("%d\n",num);
listOfNums[listCounter] = num;
currentSize += 1;
listCounter += 1;
//if( isPrime(num)) count ++;
}
struct sum_struct args[nThreads];
int * removeNums = listOfNums;
int divider = currentSize/nThreads;
int lastThread = nThreads -1;
int takeOutSize = 0;
//first initialize the takeOuts
for (int j = 0; j < nThreads; j++){
if(j == lastThread){
args[j].takeNum = removeNums;
}else{
args[j].takeNum = takeOut(removeNums,divider);
removeNums = &removeNums[divider];
}
}
// Launcher Thread
pthread_t tids[nThreads];
for (int i = 0; i < nThreads; i++){
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tids[i], &attr, sum_runner, &args[i]);
}
for (int i = 0; i < nThreads; i++) {
pthread_join(tids[i], NULL);
printf("\nSum for thread %d is %11d\n", i, args[i].answer);
count += args[i].answer;
}
//int test = 5%3;
//printf("%d",test);
//return 0;
printf("Found %ld primes.\n", count);
return 0;
}
为了详细说明它的作用,基本上我的代码countPrimes.c将接收一个文件并接受 1 个 int 参数。所以代码应该是这样的: compile: gcc countPrimes.c -o2 -o count -lm -lpthread
run: ./count < test.txt 5
where test.txt contains the contents: 1 2 3 4 5 6 7 8 9 10 100 101 102 103 104 105 106 107。回到正轨,我的代码想要做的是使用多线程,这样每个线程都会占用total amount of nums / # of threads. 所以在这种情况下,它会是18 / 5,所以所有线程都将采用数组的 3 个索引(它们从 OG 数组中删除它们),除了最后一个数组,它会占用数组中剩余的任何内容。在这一切完成之后,它运行启动p_thread tids每个线程的线程将被发送到sum_runner函数并扫描给定的所有值,takeNum它将使用isPrime找出哪些是素数。在上述情况下,我应该期待 7 个素数,但我没有,我已经尝试了从调试到在行之间放置 print 语句以查看我正在生成的错误但我似乎无法找到的所有内容这个问题,我真的可以使用一些帮助。