1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
#include <pthread.h>
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#define NBTHREADS 4
using namespace std;
struct data
{
int MAX;
int MIN;
bool* pTab;
pthread_mutex_t mut;
int i;
};
void initialiserTab(bool tab[], const int* MAX)
{
for (int i = 0; i < *(MAX)+1; i++)
tab[i] = true;
}
void affNbrPremiers(bool tab[], const int* MAX)
{
cout << "Nombres premiers jusque " << *(MAX) << " :" << endl;
for (int i = 0; i < *(MAX)+1; i++)
{
if (tab[i])
cout << i << "\t ";
}
cout << endl;
}
void *task (void* p)
{
struct data *p_data = (struct data *) p;
if (p != NULL)
{
pthread_mutex_lock (&p_data->mut);
while ((p_data->MIN)%(p_data->i) != 0)
{
p_data->MIN = p_data->MIN + 1;
}
for (int j = 2*p_data->i; j < p_data->MAX+1; j = j + p_data->i)
p_data->pTab[j] = false;
pthread_mutex_unlock (&p_data->mut);
}
return (NULL);
}
int main(int argc, char **argv)
{
const int MAX = atoi(argv[1]);
bool tab[MAX+1];
pthread_t thtab[NBTHREADS];
unsigned int partSize = MAX / NBTHREADS;
struct data * myStructs = new struct data[NBTHREADS];
for (unsigned int i=0; i<NBTHREADS ; ++i) //Initialisation Structure
{
myStructs[i].pTab = tab;
myStructs[i].mut = PTHREAD_MUTEX_INITIALIZER;
if(i > 0) //Interval MAX
myStructs[i].MAX = myStructs[i-1].MAX + partSize;
else
myStructs[i].MAX = partSize;
if (i > 0) //Interval MIN
myStructs[i].MIN = myStructs[i].MAX - partSize;
else
myStructs[i].MIN = 2;
}
if (MAX%NBTHREADS != 0) //Si le nombre MAX n'est pas divisible équitablement, alors on augmente l'interval MAX du dernier thread.
myStructs[NBTHREADS-1].MAX = (myStructs[NBTHREADS-1].MAX) + (MAX%NBTHREADS);
initialiserTab(tab, &MAX); //Initialisation du tableau
tab[0] = false;
tab[1] = false;
for (int i = 2; i < MAX+1; i++) //Crible d'Eratosthène
{
if (tab[i])
{
for (unsigned int y = 0; y < NBTHREADS; y++)
{
myStructs[y].i = i; //Initialisation de l'élemént i de la structure au nombre premier i.
pthread_create (&thtab[y], NULL, task, &myStructs[y]); //Création des threads
}
for (unsigned int z = 0; z < NBTHREADS; z++) //Attente des threads
pthread_join (thtab[z], NULL);
}
}
affNbrPremiers(tab, &MAX);
delete[] myStructs;
return (0);
} |
Partager