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