0
I’m trying to get this code to run the function calculaPrimo() on each thread in parallel to find prime numbers in a range of 1 up to the maximum value passed via command line, for example if the user put the maximum value as 100 and the number of maximal threads as 2 I wanted to make thread 1 analyze the numbers: 1,3,5... and thread 2 the numbers:2,4,6... but what is happening is that each thread is going through the interval again resulting in that output:
follows the code below:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *calculaPrimo(void *limitValue) {
int primo, j;
int num = 1;
int maxValue = *(int*)limitValue;
while (num <= maxValue) {
primo = 1;
for (j = 2; j < num && primo; j++) {
if (num % j == 0) {
primo = 0;
}
}
if (primo == 1) {
printf("%d ", num);
}
num++;
}
printf("\n");
return NULL;
}
void criaThreads(char* const* args) {
int maxValue;
int maxThreads;
long t;
pthread_t *threads;
maxValue = atoi(args[1]);
maxThreads = atoi(args[2]);
printf("Maximum integer %d\n", maxValue);
printf("Number of threads %d\n", maxThreads);
threads = (pthread_t *)calloc(sizeof(pthread_t), maxThreads);
for (t = 0; t < maxThreads; t++) {
pthread_create(&threads[t], NULL, calculaPrimo, &maxValue);
}
for (t = 0; t < maxThreads; t++) {
pthread_join(threads[t],NULL);
}
}
int main(int argc, char* const* argv) {
if (argc < 3) {
printf("%s: insufficient parameters. Please inform maximum value and number of threads\n", argv[0]);
return 1;
}
criaThreads(argv);
pthread_exit(NULL);
return 0;
}
But are these threads even working in parallel? On your console they appear to be printing the results sequentially, if they were running in parallel the values would be printed interchangeably.
– Andre
It seems to me that all threads are receiving the same maxValue parameter, so it is expected that all threads will repeat the same work.
– epx