I just started at college to study a little bit about threads, and it seems that I don't quite get the hang of it.
I wanted for my code to get the arguments and check if they are either even or prime numbers, and if they are, to print them. Additionally make the sum of each one of these kind of numbers.
This is the code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define something 10
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
int snrp=0;
int sprim=0;
void * verif(void* argv){
pthread_mutex_lock(&lock);
int x=*(int*)argv;
if (x%2==0){
printf("%d is even\n",x);
snrp+=x;
}
else{
int ok=1;
int d;
if(x<1)
ok=0;
for(d=3;d*d<x;d+=2)
if(x%d==0)
ok=0;
if(ok==0)
return NULL;
printf("%d is prime\n",x);
sprim+=x;
}
pthread_mutex_unlock(&lock);
sleep(1);
return NULL;
}
int main(int argc,char* argv[]){
pthread_t threads[something];
int i,n;
for(i=1;i<argc;i+=1){
n=atoi(argv[i]);
if(pthread_create(&threads[i],NULL,verif,(void*) &n))
printf("Error");
}
for(i=1;i<argc;i+=1)
pthread_join(threads[i],NULL);
printf("Even numbers sum is %d \n",snrp);
printf("Prime numbers sum is %d \n",sprim);
pthread_mutex_destroy(&lock);
return 0;
}
If I use for example the arguments 2,3,5
I get the output:
5 is prime
5 is prime
5 is prime
Even numbers sum is 0
Prime numbers sum is 15
Can someone please explain why?