/*** * Using multiple threads to copy files * Compile: gcc -o copyc.exe exmutex.c -pthread ***/ #include #include #include #define MAX 5 #define BLOCK 1024 void * read_file( void *); /*** This is global ***/ pthread_mutex_t lock_it = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char *argv[]) { int i; int save_status = 0; pthread_t thread_id[MAX]; void *result; //Need a place to store the return value from each thread if ( argc < 2 || argc > MAX+1 ) /* check arg list */ fprintf(stderr,"%s arg1, arg2, ... arg%d\n", *argv, MAX ), exit( 1 ); printf("Copying the files named on the command line\n\n"); for (i = 0; i < argc - 1; ++i) { /* generate threads */ if( pthread_create(&thread_id[i], NULL, read_file, (void *) argv[i + 1]) != 0) fprintf(stderr, "pthread_create failure\n"), exit( 2 ); } for (i = 0; i < argc - 1; ++i){ /* wait for each thread */ if ( pthread_join(thread_id[i], &result) > 0 ) { printf("pthread_join failure\n"); exit(3); } if ((*(int*)result) > save_status) { save_status = *((int*)result); printf("Thread %d returns %d\n", i,*((int*)result)); } free((int*)result); //Have to free memory allocated in the thread } pthread_mutex_destroy(&lock_it); //The mutex is no longer needed if (save_status == 0 ) printf("\nAll files copied\n"); exit (0); } /*** * Open and copy to stdout the contents of the file ***/ void *read_file(void *filename) { char buffer[BLOCK]; FILE* fp; int *ip = (int*)malloc(sizeof(int)); //This pointer will point at the return value pthread_t tid; ssize_t bytes_read; *ip = 0; //Initialize the return value to zero tid = pthread_self(); //What is the thread ID? if((fp = fopen((char *)filename,"r")) == NULL ) { //Try to open the external file // open was unsuccessful, so return a value of 1 *ip = 1; pthread_exit((void *)ip); } pthread_mutex_lock(&lock_it); /*lock stdout */ printf("Thread %2d copying file %s\n",(int)tid,(char *)filename); pthread_mutex_unlock(&lock_it); /*unlock stdout */ //This loop uses fgets() to read a line into the array buffer pthread_mutex_lock(&lock_it); /*lock stdout */ while ((fgets(buffer,BLOCK,fp)) != NULL) printf("%s",buffer); pthread_mutex_unlock(&lock_it); /*unlock stdout */ fclose(fp); //The file has been read // The value of ip should still be 0 return (void *)ip; }