我想要更改此程序,以便如果用戶輸入數字N,它將使素數達到N值。因爲我是新手,我無法想象它。請向我解釋我錯過了什麼。 MAX_PRIME是我的輸入參數,候選人是我想要計算的素數。使用pthread進行主數量計算但得到錯誤結果
#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);
}
我建議你應該適當地格式化你的代碼。 – MikeCAT
我很困難,我對此很新。 – KBnd
你的程序有什麼問題?它是否編譯?它運行嗎?你明白它在做什麼?你嘗試過調試嗎?你忘了問一個問題,這使我們很難回答。 –