显然,OP已经在评论中得到了答案,现在问题已经解决。
我编写了一个使用 pthread 执行的素数程序(eratosthenes 筛)。
这是我的第一个多线程程序,我不知道为什么我的程序大约需要 3 分钟。执行的时间。时间太长了!
有人可以告诉我我到底错在哪里:
#include<iostream>
#include<cstring>
#include<pthread.h>
#include<time.h>
using namespace std;
//set limits
#define LIMIT 100000001
#define THREAD_LIMIT 8
//declare buffers
bool num[LIMIT];
unsigned long long num_of_prime = 1; // 2 is counted as prime initially
unsigned long long sum_prime = 2; // 2 is counted in sum of primes
void *search(void *);
int main()
{
clock_t start_time = clock(); // start clock stamp
pthread_t thread[THREAD_LIMIT];
int thread_val=-1,j=-1;
unsigned long long i=3;
bool *max_prime[10]; // stores max. 10 prime numbers
memset(num,0,LIMIT); // initialize buffer with 0
while(i<LIMIT)
{
if(num[i]==0)
{
num_of_prime++;
sum_prime +=i;
j = ++j%10;
max_prime[j]=num+i;
thread_val=++thread_val%THREAD_LIMIT;
pthread_join(thread[thread_val],NULL); // wait till the current thread ends
pthread_create(&thread[thread_val],NULL,search,(void *)i); // fork thread function to flag composite numbers
}
i+=2; // only odd numbers
}
// end all threads
for(i=0;i<THREAD_LIMIT;i++)
{
pthread_join(thread[i],NULL);
}
cout<<"Execution time: "<<((double)(clock() - start_time))/CLOCKS_PER_SEC<<"\n";
cout<<"Number of Primes: "<<num_of_prime<<"\n";
cout<<"Sum of Primes: "<<sum_prime<<"\n";
cout<<"List of 10 Max. Primes: "<<"\n";
for(i=0;i<10;i++)
{
j=++j%10;
cout<<(max_prime[j]-num)<<"\n";
}
return 0;
}
void *search(void *n)
{
unsigned long long jump = (unsigned long long int)n;
unsigned long long position = jump*jump; // Jump to N*N th comppsite number
bool *posn = num;
jump<<=1;
while(position<LIMIT)
{
(*(posn+position))?(position+=jump):(*(posn+position)=1,position+=jump);
}
return NULL;
}
约束:只能分叉 8 个线程。
数量:10^8
如何提高此代码的效率(尤其是在分叉和加入线程时)?