/****************************************************************************** * FILE: hellox.c * DESCRIPTION: * A pThreads program to demonstrate use of mutex objects to protect access * to a file. * AUTHOR: Dr. Spiegel * LAST REVISED: 03/10/07 ******************************************************************************/ #include #include #include // These declarations must be global; parameter of thread fn is predetermined pthread_mutex_t mutex; void *PrintHello(void *threadid) { printf("\n%d: Writing to file\n", threadid); // Open a file to write stuff to. FILE *TheFile; TheFile=fopen("thread.txt","a"); pthread_mutex_lock(&mutex); fprintf(TheFile,"Thread %d writes to file\n", threadid); pthread_mutex_unlock(&mutex); fclose(TheFile); pthread_exit(NULL); } int main(int argc, char *argv[]) { // Check for single command line argument if (argc<2) { printf("Form: hellox <# threads>\n"); exit(1); } int rc=0; printf("Create the mutex using default mutex attributes \n"); rc = pthread_mutex_init(&mutex,NULL); if (rc!=0) { perror("Mutex not initialized"); exit(-1); } int numThreads=atoi(argv[1]); pthread_t *threads=malloc(sizeof(pthread_t)*numThreads); int t; for(t=0;t