Skip to content

Instantly share code, notes, and snippets.

@hgfernan
Last active July 8, 2021 15:00
Show Gist options
  • Save hgfernan/ddd4681a6f7b7ec5f3380833909f4221 to your computer and use it in GitHub Desktop.
Save hgfernan/ddd4681a6f7b7ec5f3380833909f4221 to your computer and use it in GitHub Desktop.
/* From https://pt.stackoverflow.com/questions/516989/c%c3%b3digo-compila-mas-n%c3%a3o-funciona-apenas-finaliza-com-sucesso */
#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;
}
@hgfernan
Copy link
Author

hgfernan commented Jul 8, 2021

File edited according to C90, aka ANSI C.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment