Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* I pledge my Honor that I have abided by the Stevens Honor System -Paul Chua
- * cs392_thread.c
- *
- * Created on: Apr 17, 2019
- * Author: StevensUser
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <string.h>
- int item1_counter,item2_counter,item3_counter = 0;
- pthread_mutex_t m;
- void* cs392_run_thread(void * arg){
- //Read each line
- FILE *fp;
- int s;
- char * buffer;
- ssize_t line;
- size_t line_buf_size = 0;
- //Open file and give error if you can't open it
- fp = fopen(arg,"r");
- if(fp ==NULL){
- perror("Error opening file");
- }
- pthread_mutex_lock(&m);
- line = getline(&buffer, &line_buf_size, fp);
- //While there is still content in the file, adjust counters based off of what it reads
- while(line >= 0){
- if (strcmp(buffer,"+item3\n") == 0){
- item3_counter++;;
- }
- else if( strcmp(buffer,"-item3\n") == 0){
- item3_counter--;
- }
- else if( strcmp(buffer,"+item2\n") == 0){
- item2_counter++;
- }
- else if( strcmp(buffer,"-item2\n") == 0){
- item2_counter--;
- }
- else if( strcmp(buffer,"+item1\n") == 0){
- item1_counter++;
- }
- else if( strcmp(buffer,"-item1\n") == 0){
- item1_counter--;
- }
- //If for some reason, you dont get the +item1 stuff, exit the program and tell the user something is unreadable
- else{
- printf("Content is wrong");
- exit(1);
- }
- //Move onto the next line
- line = getline(&buffer, &line_buf_size, fp);
- }
- pthread_mutex_unlock(&m);
- pthread_exit(NULL);
- return NULL;
- }
- int main(int argc, char **argv){
- //Error for when not enough arguments
- if (argc != 4){
- perror("Not enough arguments");
- }
- //Error if mutex fails
- if(pthread_mutex_init(&m, NULL) != 0){
- printf("Mutex init failed");
- }
- //Create threads and run the threads using the various arguments
- pthread_t thread1,thread2,thread3;
- int iret1,iret2,iret3;
- iret1 = pthread_create(&thread1,NULL,cs392_run_thread,argv[1]);
- iret2 = pthread_create(&thread2,NULL,cs392_run_thread,argv[2]);
- iret3 = pthread_create(&thread3,NULL,cs392_run_thread,argv[3]);
- //Join them
- pthread_join(thread1,NULL);
- pthread_join(thread2,NULL);
- pthread_join(thread3,NULL);
- //Print the result and destroy mutex
- pthread_mutex_destroy(&m);
- printf("The final value of item1_counter, item2_counter, and item3_counter are %d, %d, and %d", item1_counter, item2_counter, item3_counter);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement