我:多線程素數生成器
input1: n to generate primes up to
input2: no of threads to generate primes
我實現了這一點,它的工作原理,但問題是,每一個線程生成自己的素數[2, n]
的名單。
但我希望這兩個線程都能處理產生素數的相同任務,而不是彼此獨立切換。如何將n
分成多個線程?
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void *BusyWork(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread # %ld\n", tid);
double s,d;
int n,i,c,k,p,cs,nsqrt;
printf("Input an integer n > 1 to generate primes upto this n: "); // prompt
scanf("%d",&n);
printf("Entered integer: %d\n",n);
int array[n];
for(i=0;i<n;i++)
array[i]=0;
s=sqrt(n);
d=floor(s);
nsqrt = (int) d;
for (c= 2; c <= nsqrt; c++)// note here < is not working <= is working here.
{
if(array[c]==0)
{
cs = c*c;
k=0;
for(p=cs; p<n; p=(cs+k*c))
{
k++;
array[p] = 1;
}//for
}//if
}//for
for (i = 2; i < n; i++)
{
if (array[i]==0)
{
printf("%5d",i);
}//if
}// for
printf("\n");
printf("Above prime numbers are generated from me i.e. thread # %ld GOOD BYE!!! \n ", tid);
pthread_exit((void*) threadid);
}
int main (int argc, char *argv[])
{
//////// time cal ///////////////////
struct timespec start, finish;
double elapsed;
clock_gettime(CLOCK_MONOTONIC, &start);
/////////////////////////////////////
int NUM_THREADS;
printf("Please Input Total Number of Threads you want to make:- ");
scanf("%d",&NUM_THREADS);
pthread_t thread[NUM_THREADS];
pthread_attr_t attr;
int rc;
long t;
void *status;
/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(t=0; t<NUM_THREADS; t++) {
printf("Main: creating thread %ld\n", t);
rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Free attribute and wait for the other threads */
pthread_attr_destroy(&attr);
for(t=0; t<NUM_THREADS; t++) {
rc = pthread_join(thread[t], &status);
if (rc) {
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
printf("Main: completed join with thread %ld having a status of %ld\n",t, (long)status);
}
printf("Main: program completed. Exiting.\n");
////////////// time end ////////////////////////
clock_gettime(CLOCK_MONOTONIC, &finish);
elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
printf("Total time spent by the main: %e \n", elapsed);
//////////////////////////////////////////////////////////
pthread_exit(NULL);
}
您將需要在線程之間或主要候選人的範圍之間派發工作包(主要候選人)。在候選人足夠大之前,或者素質測試更復雜,你不太可能看到太多的好處。 –
我不想在素數沒有幫助。生成部分。我喜歡有一個提示:我想同時生成素數列表,因爲如果某個線程生成一些素數不是從其他線程生成的。 – mAge
@mAge:所以劃分數字列表來檢查一半。 –