00001
00016
00017 #include <pthread.h>
00018 #include <errno.h>
00019 #include <unistd.h>
00020 #include <fcntl.h>
00021 #include <sys/stat.h>
00022 #include <sys/types.h>
00023 #include <sys/ioctl.h>
00024 #include <stdio.h>
00025 #include <stdlib.h>
00026
00027 #include "CommanHeader.h"
00028
00029 int main()
00030 {
00031 ThreadParam threadParams[MAX_CLIENTS + 1];
00032 pthread_t threadID[MAX_CLIENTS + 1];
00033 int i = 0;
00034 int noOfConsumers = 0;
00035 int noOfItems = 0;
00036 int totalItems = 0;
00037 int ret = 0;
00038 int exitReason = 0;
00039 sem_t semLock;
00040 pthread_attr_t threadAttr;
00041
00042 if( sem_init( &semLock, 0, 1 ) != 0 )
00043 {
00044 printf("Error Creating semaphore");
00045 exit(-1);
00046 }
00047
00048
00049 printf("Enter Number of Consumers : ");
00050 scanf("%d", &noOfConsumers);
00051
00052 if(MAX_CLIENTS < noOfConsumers)
00053 {
00054 noOfConsumers = MAX_CLIENTS;
00055 }
00056
00057 for(i=1; i<=noOfConsumers; i++)
00058 {
00059 printf("Items Needed by Consumer-%d : ", i);
00060 scanf("%d", &noOfItems);
00061 totalItems += noOfItems;
00062
00063 threadParams[i].noOfItems = noOfItems;
00064 threadParams[i].itemLock = semLock;
00065 threadParams[i].noOfConsumers = i;
00066 }
00067
00068
00069 threadParams[0].noOfItems = totalItems;
00070 threadParams[0].noOfConsumers = noOfConsumers;
00071 threadParams[0].itemLock = semLock;
00072
00073 pthread_attr_init( &threadAttr );
00074 pthread_attr_setdetachstate( &threadAttr, PTHREAD_CREATE_JOINABLE );
00075
00076
00077 ret = pthread_create( &threadID[0], &threadAttr, ProducerThreadEntryPoint,
00078 (void*)&threadParams[0] );
00079
00080 if(ret != 0)
00081 {
00082 printf("Error Creating Producer Thread");
00083 exit(-1);
00084 }
00085
00086
00087 for(i=1; i <= noOfConsumers; i++)
00088 {
00089 ret = pthread_create( &threadID[i], &threadAttr, ConsumerThreadEntryPoint,
00090 (void*)&threadParams[i] );
00091
00092 if(ret != 0)
00093 {
00094 printf("Error Creating Consumer Thread %d", i);
00095 exit(-1);
00096 }
00097 }
00098
00099
00100 CreateObserverThread (totalItems * 2);
00101
00102
00103 for(i=0; i<=noOfConsumers; i++)
00104 {
00105 ret = pthread_join(threadID[i], (void**)&exitReason );
00106 }
00107
00108
00109 sem_destroy( &semLock );
00110 printf("Completed the Production/Consumption..\n Press Any Key to Exit");
00111 getchar();
00112 getchar();
00113 return 0;
00114 }
00115
00116