#include #include #include #include #include #include #include /* Some files we will write to */ #define OUT_T1 "fprint.out" #define OUT_T2 "write.out" /* Our thread functions */ void *thread1 (void *arg); void *thread2 (void *arg); /* some mutex to make the code more interesting */ pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int counter = 0; int main(int argc, char *argv[]) { /* * We define the thread identifiers which are later used as * in the call to to create threads. */ pthread_t thr1, thr2; char *message1 = "Thread 1"; char *message2 = "Thread 2"; /* * Create threads using default values for the attributes, * (specified by setting NULL as the argument in the call). * Making sure we check for errors! */ if(pthread_create( &thr1, NULL, thread1, (void *)message1)){ printf("Creation of thread %s failed. \n",message1); } if(pthread_create( &thr2, NULL, thread2, (void *)message2)){ printf("Creation ot thread %s failed. \n",message2); } /* * Wait for all threads to finnish before exiting main */ pthread_join(thr1, NULL); pthread_join(thr2, NULL); return 0; } /* Our first thread */ void *thread1 (void *arg) { long i; FILE *fp; if ((fp=fopen(OUT_T1,"w")) == NULL) { fprintf(stderr,"Can't open %s. Bye.\n",OUT_T1); pthread_exit((void *) arg); } for (i=0; i<300000; i++) { /* write 300,000 Xs with fprintf */ if (fprintf(fp,"X") < 1) { fprintf(stderr,"Can't write. Bye\n"); pthread_exit((void *) arg); } } fclose(fp); /* Lock the resource, by use of mutex */ pthread_mutex_lock(&mutex1); counter++; printf ("Thread finishing = %s, with counter at: %d \n", (char *)arg,counter); /* Unlock when we're done */ pthread_mutex_unlock(&mutex1); /* Call pthread_exit() to cleanly exit the thread */ pthread_exit((void *) arg); } /* Our second thread */ void *thread2 (void *arg){ long i; int fd; if ((fd=open(OUT_T2,O_WRONLY|O_CREAT,0644)) < 0) { fprintf(stderr,"Can't open %s. Bye.\n",OUT_T2); pthread_exit((void *) arg); } for (i=0; i<100000; i++) { /* write 100,000 Ys with write */ if (write(fd,"Y",1) < 1) { fprintf(stderr,"Can't write. Bye\n"); pthread_exit((void *) arg); } } close(fd); /* Lock the resouce, by use of mutex */ pthread_mutex_lock(&mutex1); counter++; printf ("Thread finishing = %s, with counter at: %d \n", (char *)arg,counter); /* Unlock when we're done */ pthread_mutex_unlock(&mutex1); /* Call pthread_exit() to cleanly exit the thread */ pthread_exit((void *) arg); }