/*** * Compile: g++ -o copycpp -pthread exmutex.cpp ***/ #include #include #include #include #define MAX 5 #define BLOCK 1024 #if defined(__cplusplus) extern "C" #endif using namespace std; 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]; if ( argc < 2 || argc > MAX+1 ){ /* check arg list */ cout << "argc is " << argc << " MAX is " << MAX < (argv[i + 1])) != 0) { cout << "pthread_create failure\n"; exit( 2 ); } cout << "Created thread " << i << endl; } void *result; //Need a place to store return value from each thread for (i = 0; i < argc - 1; ++i){ /* wait for each thread */ if ( pthread_join(thread_id[i], &result) > 0 ) { cout << "pthread_join failure\n"; exit( 3 ); } if (*(static_cast(result)) > save_status) { save_status = *(static_cast(result)); cout << "Thread " << i << " returns " << *(static_cast(result)) << endl; } delete static_cast(result); //Have to free memory allocated in the thread } pthread_mutex_destroy(&lock_it); //The mutex is no longer needed if (save_status == 0 ) cout << "\nAll files copied\n"; return (0); } /*** * Open and copy to stdout the contents of the file ***/ void *read_file(void *filename) { char buffer[BLOCK]; ifstream fd; int *pfid = new int; //This address will be returned, need it to be on the heap *pfid = 0; pthread_t tid; tid = pthread_self(); //Which thread is it pthread_mutex_lock(&lock_it); /* lock stdout */ cout << "Entered the thread function, tid = " << static_cast(tid) << endl; pthread_mutex_unlock(&lock_it); /*unlock stdout */ //Open the file specified on the command line fd.open(static_cast(filename)); if(!fd) { // File open failed *pfid = 1; pthread_exit(static_cast(pfid)); } pthread_mutex_lock(&lock_it); /* lock stdout */ cout << "Thread " << static_cast(tid) << " copying file " << static_cast(filename) << endl; pthread_mutex_unlock(&lock_it); /*unlock stdout */ //The file will be copied in this loop pthread_mutex_lock(&lock_it); /* lock stdout */ while (fd.getline(buffer,BLOCK) > 0) cout << buffer << endl; pthread_mutex_unlock(&lock_it); /*unlock stdout */ fd.close(); //The file is no longer needed //*pffid should still be 0 pthread_exit(static_cast(pfid)); //Returned success }