试图创建一个多线程程序来查找0-100000000中的所有素数

问题描述 投票:0回答:1

您好,我正在尝试使用POSIX线程库编写C ++多线程程序,以找到1到10,000,000(1000万)之间的质数,并找出需要多少微秒...

创建我的线程并运行它们完全可以正常工作,但是在确定一个数字是否为质数时,我感觉好像在我的Prime函数中发现错误...

我一直接收78496作为输出,但是我希望664579。下面是我的代码。任何提示或指针将不胜感激。

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <sys/time.h> //measure the execution time of the computations

using namespace std;

//The number of thread to be generated
#define NUMBER_OF_THREADS 4

void * Prime(void* index);

long numbers[4] = {250000, 500000, 750000, 1000000};
long start_numbers[4] = {1, 250001, 500001, 750001};

int thread_numbers[4] = {0, 1, 2, 3};

int main(){
  pthread_t tid[NUMBER_OF_THREADS];

  int tn;

  long sum = 0;

  timeval start_time, end_time; 

  double start_time_microseconds, end_time_microseconds;

  gettimeofday(&start_time, NULL);

  start_time_microseconds = start_time.tv_sec * 1000000 + start_time.tv_usec;
  for(tn = 0; tn < NUMBER_OF_THREADS; tn++){
    if (pthread_create(&tid[tn], NULL, Prime, (void *) &thread_numbers[tn]) == -1 ) {
        perror("thread fail");
        exit(-1);
    }
  }
 long value[4];

 for(int i = 0; i < NUMBER_OF_THREADS; i++){
    if(pthread_join(tid[i],(void **) &value[i]) == 0){
        sum = sum + value[i]; //add four sums together
    }else{
      perror("Thread join failed");
      exit(-1);
    }
 }
 //get the end time in microseconds
 gettimeofday(&end_time, NULL);

 end_time_microseconds = end_time.tv_sec * 1000000 + end_time.tv_usec;

 //calculate the time passed
 double time_passed = end_time_microseconds - start_time_microseconds;

 cout << "Sum is: " << sum << endl;
 cout << "Running time is: " << time_passed << " microseconds" << endl;

 exit(0);
}


//Prime function
void* Prime(void* index){
  int temp_index;

  temp_index = *((int*)index);
  long  sum_t = 0;

  for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){
        for (int j=2; j*j <= i; j++)
        {
            if (i % j == 0) 
            {
                break;
            }
            else if (j+1 > sqrt(i)) {
                sum_t++;
            }
         }

  }

  cout << "Thread " << temp_index << " terminates" << endl;
  pthread_exit( (void*) sum_t);
}```
c++ multithreading posix
1个回答
0
投票

这是因为您使用10 ^ 6而不是10 ^ 7。

我用正确的数字测试了您的代码,并获得了正确的素数作为输出:

Thread 1 terminates
Thread 0 terminates
Thread 2 terminates
Thread 3 terminates
Sum is: 664577
Running time is: 2.79829e+07 microseconds
© www.soinside.com 2019 - 2024. All rights reserved.