Zamolxis666 Posted January 28, 2011 Report Posted January 28, 2011 Folosind un calculator cu N procesoare, sa se determine toate numerele prime mai mici decat o valoare data.#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <math.h>//nu strica sa le vefiric pe toate numerele prime gasite//si daca numarul prim la care vremn sa impartim se intampla as nu fie gasit inca, inseamna ca e in lucru pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;volatile int reachedIndex = 3;int limitNumber = 50;int foundPrimeNumbers[10000];int foundPrimeNumbersIndex = 0;int prim(int numar){ int prim = 1; int i, j; int squareRoot = (int) sqrt(numar); if(squareRoot == foundPrimeNumbers[foundPrimeNumbersIndex]) { prim = 0; } if(squareRoot < foundPrimeNumbers[foundPrimeNumbersIndex]) { // Daca intervalul de numere cu care vrem sa impartim este inclus // in intervalul de numere prime testate deja for(i = 0; i <= foundPrimeNumbersIndex; i++) { if(numar % foundPrimeNumbers[i] == 0) { prim = 0; break; } } if(prim == 1) { // Daca radacina numarului nu a fost inca testata. for (i = 3; i <= squareRoot; i += 2) { if (numar % i == 0) { prim = 0; break; } } } } if (squareRoot > foundPrimeNumbers[foundPrimeNumbersIndex]) { for (i = 3; i <= squareRoot; i += 2) { if (numar % i == 0) { prim = 0; break; } } } return prim;}void *primeNumbers(){ int temp; while(reachedIndex <= limitNumber) { int i, j; int number = getNumber(); if(prim(number)) { pthread_mutex_lock(&mutex); foundPrimeNumbersIndex++; foundPrimeNumbers[foundPrimeNumbersIndex] = number; for(i = foundPrimeNumbersIndex; i > 0; i--) { if (foundPrimeNumbers[i - 1] > foundPrimeNumbers[i]) { temp = foundPrimeNumbers[i]; foundPrimeNumbers[i] = foundPrimeNumbers[i-1]; foundPrimeNumbers[i-1] = temp; } } pthread_mutex_unlock(&mutex); } }}int getNumber(){ pthread_mutex_lock(&mutex2); reachedIndex += 2; if(reachedIndex > limitNumber) pthread_exit(NULL); pthread_mutex_unlock(&mutex2); return reachedIndex;}int main(){ int i; int nrThreads = 7; pthread_t threadIds[7]; foundPrimeNumbers[0] = 3; for(i = 0; i < 7; i++) { pthread_create(&threadIds[i], NULL, primeNumbers, NULL); } for(i = 0; i < 7; i++) pthread_join(threadIds[i], NULL); printf("\nThe prime numbers are\n"); for(i = 0; i <= foundPrimeNumbersIndex; i++) printf(" %d ", foundPrimeNumbers[i]);}Cod scris de mine si o colega. Quote
Guest User Name Posted January 28, 2011 Report Posted January 28, 2011 pai si nu lasi numarul colegei la drepturi de autor? Quote