gpt4 book ai didi

c - 使用 pthread 进行素数计数但得到错误的结果

转载 作者:行者123 更新时间:2023-11-30 19:40:08 25 4
gpt4 key购买 nike

我想更改此程序,以便如果用户输入数字 N,它会给出最多 N 值的素数。由于我是新手,所以我无法弄清楚。请向我解释一下我缺少什么。 MAX_PRIME 是我的输入参数,候选者是我想要计算的素数。

#include <pthread.h>
#include <stdio.h>
#include<stdlib.h>
#include<math.h>



int NUM_THREADS;
pthread_t *thread;
int MAX_PRIME;
int current = 1;
int candidate;

pthread_mutex_t thread_flag_mutex;

int get_next_candidate()
{
pthread_mutex_lock (&thread_flag_mutex);
int result=current++;
pthread_mutex_unlock (&thread_flag_mutex);

return result;
}


int compute_prime(int numPrime)
{
int candidate = 2;
while (1)
{
int factor;
int is_prime = 1;

/* Test primality by successive division. */
for (factor = 2; factor < MAX_PRIME; ++factor)
{
if (candidate % factor == 0)
{
is_prime = 0;
break;
}
}

if (is_prime)
{
if (--numPrime == 0)
{
return candidate;
}
}
++candidate;
}

return 0;
}


void* prime_job(void* t)
{

long tid = (long ) t , total = 0 , result=0;


printf("Thread %ld starting...\n", tid);

while((candidate=get_next_candidate())<=MAX_PRIME){
result=compute_prime(candidate);
printf("Thread %ld found prime: %ld\n",tid, result);

++total;
}

pthread_exit((void*) total);
}


//******************************* main
int main (int argc, char **argv)
{
if (argc<=1){
printf("usag : prime MaxNumber [NUM_THREADS]");
return 0;
}

else if (argc==2){
//setting up the default thread value
MAX_PRIME=atoi(argv[1]);
NUM_THREADS =2;
}

else{
MAX_PRIME=atoi(argv[1]);
NUM_THREADS=atoi(argv[2]);

}


//**************************** allocaion of memory

candidate = malloc((candidate+1)*sizeof(int));
thread = malloc(NUM_THREADS*sizeof(pthread_t));

long t;

// Start threads
for (t = 0; t < NUM_THREADS; t++)
pthread_create(&thread[t], NULL, prime_job, (void *) t);

// Join threads
for (t = 0; t < NUM_THREADS; t++)
{
void* numPrimesCalc;
pthread_join(thread[t], &numPrimesCalc);
printf("Thread %ld joined, calculated %ld prime numbers\n", t, (long) numPrimesCalc);
}

/* Print the largest prime it computed. */

pthread_exit(NULL);
}

最佳答案

int compute_prime(int numPrime)
{
int candidate = 2;
while (1)
{
int factor;
int is_prime = 1;

/* Test primality by successive division. */
for (factor = 2; factor < MAX_PRIME; ++factor)
{
if (candidate % factor == 0)

如果您尝试测试 numPrime 是否为素数,则 numPrime 需要位于 % 的左侧。否则,您测试的数字完全错误。

您的 for 循环需要在您的测试数字之前停止。对于所有大于零的 xx % x 将为零。因此,如果您测试的因子包含要测试素数的数字,您将永远找不到任何素数。

另外,while (1) 到底是做什么用的?这段代码看起来像是 cargo 崇拜编程的结果,其中放置了一些东西,因为它们帮助解决了完全不同的问题,而无需理解。

关于c - 使用 pthread 进行素数计数但得到错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35791962/

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