Hi guys, I'm trying to make a script that uses 3 threads that have the task of searching and sending to a memorizer via a pipe, the prime numbers up to a certain n (passed as an input parameter). All 3 threads must work at the same time.
I have 2 problems basically ...
The first is that the threads don't analyze all the numbers, some are skipped, I don't understand why.
The second is that if I launch the main file and then the memorizer, they both stay planted and give no output.
Could you please help me?
Main file
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int num, n ;
int fp ;
void *find_prime_number (void* name){
int *th = (int *) name;
//while(num <= n ){
int mynum;
while (pthread_mutex_lock(&mutex), mynum = num++, pthread_mutex_unlock(&mutex), mynum <= n)
{
int check = 0;
////
for(int i=2 ;i<=num/2; i++ ){
if(num<=n){
if (num % i==0 ){
printf("Calc%d : %d NON è un numero primo \n", *th, num);
check=1;
break;
}
}
else{
return 0 ;
}
}
/////
if (num<=n){
if(check == 0){
printf("Calc%d : %d è un numero primo , lo invio al memorizzatore\n", *th, num);
write (fp, &num , sizeof(num));
}
}
else {
return 0 ;
}
if(num <= n){
num++;
}
}
}
int main(int argc , char *argv[]){
char *fifo = "myfifo" ;
if (argc != 2 ){
printf("Errore nell'immissione dei parametri \n ");
return -1 ;
}
int error ;
n= atoi(argv[1]);
pthread_t t1 , t2 , t3 ;
pthread_t *calc_arr[3] = { &t1 , &t2 , &t3 } ; //array per l'id dei thread
if (error = mkfifo( fifo , 0666)== -1){
// printf("Errore nella pipe fifo \n");
perror(fifo);
if (errno != EEXIST){
return -1;
}
}
if ((fp = open(fifo, O_RDONLY))==-1 ){
perror(fifo);
//if (errno != EEXIST)
//return -1 ;
return 1;
}
int thread[]= {1,2,3};
for(int i = 0; i<3 ; i++ ){
if(error = pthread_create(calc_arr[i], NULL,find_prime_number,&thread[i]) != 0 ){
perror("Errore nella creazione dei thread");
exit(1);
}
}
for (int i = 0; i < 3 ; i++){
if (error=pthread_join(*calc_arr[i], NULL )!= 0 ){
perror("Errore nel join dei thread ");
exit(1);
}
}
close(fp);
printf("Terminazione dei calcolatori \n");
return 0 ;
}
Memorizer.c
Code:
#include <fcntl.h>#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
#define MAX_PID 8
int main()
{
int fd ;
int bytesread;
char * myfifo = "myfifo";
char buf[MAX_BUF];
fd = open( myfifo, O_RDONLY );
while(1)
{
if((bytesread = read( fd, buf, MAX_BUF - 1)) > 0)
{
buf[bytesread] = '\0';
printf("Received: %s\n", buf);
}
else
break;
}
close(fd);
return 0;
}