diff --git a/fact.c b/fact.c index 58475893769d6ebabdef41293248eef7e317e6ca..64113a14bd9ce63ca90adeac96a87a57ef40a66f 100644 --- a/fact.c +++ b/fact.c @@ -1,5 +1,5 @@ // -// Modified on 24/04/2020. +// Modified on 26/04/2020. // #include <errno.h> #include <sys/types.h> @@ -141,7 +141,7 @@ void *read_write() { fprintf(f.out, "\n"); free(dividers); } else { - fprintf(f.out, "The number %lu is not > 2, discarded \n", number); + fprintf(f.out, "The number %lu is not > 2, discarded\n", number); } } pthread_exit((void *) 0); // thread exit: normal termination => 0 @@ -166,4 +166,70 @@ int main (int argc, char *argv[]) { inputfile = argv[1]; outputfile = argv[2]; printf("Thread number not mentioned\n"); - printf("The default threads number is %d\n", DEFAULT_NO_THREADS); \ No newline at end of file + printf("The default threads number is %d\n", DEFAULT_NO_THREADS); + } else if(argc == 5) { + thread_arg = argv[1]; + if(strcmp(thread_arg, "-N") != 0) { + printf("%s\n", "Wrong input of the option\n Use option \"-N\"\n"); + exit(EXIT_FAILURE); + } + NO_THREADS = atoi(argv[2]); + if(NO_THREADS > MAX_NO_THREADS) { + printf("Threads requested > %d\n", MAX_NO_THREADS); + exit(EXIT_FAILURE); + } + inputfile = argv[3]; + outputfile = argv[4]; + } else { + printf("%s\n", "Many or few arguments\n"); + printf("Correct command syntax:\n"); + printf("./fact [-N number_of_threads] input_file.txt output_file.txt\n\n"); + exit(EXIT_FAILURE); + } + /* + * START CLOCK to measure CPU time + * calculate programme performance + */ + /* + clock_t start, end; + double cpu_time_used; + start = clock(); + */ + // Open input and output files + f.in = fopen(inputfile, "r"); + f.out = fopen(outputfile, "a+"); + if ((f.in == NULL) || (f.out == NULL)) { + printf("Incorrect input_file or output_file name\n"); + exit(EXIT_FAILURE); + } + + pthread_t thread[NO_THREADS]; // thread IDs + // INITIALIZE MUTEX "mutex_readwrite" + if (pthread_mutex_init(&mutex_readwrite , NULL) != 0){ + printf("\n mutex init failed-mutex_readwrite\n"); + exit(EXIT_FAILURE); + } + int i; + for (i = 0; i < NO_THREADS; i++) { + pthread_create(&thread[i], NULL, (void*)read_write, NULL); + } + for (i = 0; i < NO_THREADS; i++) { + pthread_join(thread[i], NULL); + } + /* END CLOCK to measure CPU time */ + /* + end = clock(); + cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; + fprintf(f.out, "\nThe programme execution needed %.3f seconds\n\n", cpu_time_used); + printf("\nThe programme execution needed %.3f seconds", cpu_time_used); + printf("\n -- Programme end --\n"); + */ + // Eliminate mutex "mutex_readwrite" + if (pthread_mutex_destroy(&mutex_readwrite) != 0){ + printf("\nmutex_destroy-mutex_readwrite %s\n", strerror(errno)); + exit(EXIT_FAILURE); + } + fclose(f.in); + fclose(f.out); + return (EXIT_SUCCESS); +} \ No newline at end of file