у меня есть:многопоточного генератора простое число
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: Разделите список чисел, чтобы проверить пополам. –