0
Well I am new to the C language and I decided to venture into the world of multithreads, I thought of making a program that would find primes in a range from 1 to N, and for that I would divide the task into X threads. For this the user would need to pass via commandline the N and the number of threads, so I wrote the code below but it compiles without errors but does not work as expected, even if I put a prinf("test") at the beginning of the main() function it does not appear in the console, what’s going on and where I went wrong?
I’m using a C compiler online and passing 100 and 32 to N and number of threads respectively
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *calculaPrimo(void *limitValue) {
int primo, j;
int num = 1;
int maxValue = 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");
}
void criaThreads(char *args[]) {
int maxValue = atoi(args[1]);
int maxThreads = atoi(args[2]);
printf("%d , %d", maxValue, maxThreads);
long t;
pthread_t threads[maxThreads];
for (t = 0; t < maxThreads; t++) {
pthread_create(&threads[t], NULL,(void * ) calculaPrimo, &maxValue);
}
for (t = 0; t < maxThreads; t++) {
pthread_join(threads[t],NULL);
}
}
int main(int argc, int argv[]) {
char *args[] = {argv[0], argv[1], argv[2]};
criaThreads(args);
pthread_exit(NULL);
return 0;
}
How are you compiling? Which compiler? What arguments are you passing to start the application?
– Higor Maia Concessa
I edited the question with this information
– Bruno D.
One mistake I see is
char *args[] = {argv[1], argv[2]}
, here you take the second and third argument, if you pass only two, the third is null. In this context the correct one would bechar *args[] = {argv[0], argv[1]}
. Ensure your parameters are correct inargv
.– Higor Maia Concessa
I fixed it however I keep getting a warning: initialization makes Pointer from integer without a cast
– Bruno D.
@Brunod. Actually the ideal is to check the
argc
to see if the amount of arguments is what you need (if calling the program without arguments, it is no use trying to catch theargv[1]
,argv[2]
, etc - in C, this may not give error, but generates undefined behavior). And in themain
, sure ischar *argv[]
and notint *argv[]
. Anyway, here’s the tip I already gave below: as you’re starting out, first study the basics of the language and only then go for more complicated things (like threads and pointers)– hkotsubo