/* ================================================================= Reader/writer ================================================================= */ #include #include #include #define N 1000000 #define MAX 10 int nItems = 0; // Number of items in buffer int buf[MAX]; int writePtr, readPtr; pthread_mutex_t mutex; // Protect nItems pthread_mutex_t Wr; // Used to block writer pthread_mutex_t Rd; // Used to block reader void *writer(void *arg) { int i, x, sum; sum = 0; for ( i = 0; i < N; i++ ) { x = rand()%100; // Produce an item sum += x; pthread_mutex_lock(&mutex); // Block writer if ( nItems == MAX ) { // Buffer is full pthread_mutex_lock(&Wr); // Block writer // Redaer must unblock it ! } buf[writePtr] = x; // Put x in buffer writePtr = (writePtr+1) % N; if ( UNBLOCK reader; } } /* ======================= MAIN ======================= */ int main(int argc, char *argv[]) { int i, num_threads; pthread_t tid[100]; /* Thread ID used for thread_join() */ int param[100]; /* used to store parameters for threads */ pthread_attr_t attr; pthread_attr_init(&attr); /* ----- Check command line ----- */ if ( argc != 2 ) { cout << "Usage: " << argv[0] << " Num_Threads" << endl; exit(1); } /* ----- Get number of intervals and number of threads ----- */ num_threads = atoi(argv[1]); /* ------ Create threads ------ */ for (i = 0; i < num_threads; i = i + 1) { param[i] = 1001 + i; if ( pthread_create(&tid[i], &attr, worker, ¶m[i]) ) { cout << "Cannot create thread" << endl; exit(1); } } for (i = 0; i < num_threads; i = i + 1) pthread_join(tid[i], NULL); }